<?php

namespace OtomaticAi\Models;

use OtomaticAi\Vendors\Illuminate\Database\Eloquent\Model;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class Template extends Model
{
    protected $fillable = [
        "name",
        "plugin_version",
        "payload"
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['single_mode_formatted_payload'];

    protected $casts = [
        'payload' => 'array',
    ];

    /**
     * Create a new Eloquent model instance.
     *
     * @param  array  $attributes
     * @return void
     */
    public function __construct(array $attributes = [])
    {
        global $wpdb;

        $this->table = $wpdb->prefix . 'otomatic_ai_templates';
        parent::__construct($attributes);
    }

    public function getPayloadAttribute()
    {
        $payload = json_decode($this->attributes["payload"], true);
        $modules = Project::makeModules('bulk', Arr::get($payload, "modules"));

        Arr::forget($modules, "autopilot");

        return [
            "persona_id" => Arr::get($payload, "persona_id"),
            "modules" => $modules,
        ];
    }

    public function getSingleModeFormattedPayloadAttribute()
    {
        $payload = json_decode($this->attributes["payload"], true);

        return [
            "persona_id" => Arr::get($payload, "persona_id"),
            "settings" => SingleModeGeneration::modulesToSettings(Project::makeModules('bulk', Arr::get($payload, "modules"))),
        ];
    }
}
