<?php

namespace OtomaticAi\Controllers\SingleMode;

use OtomaticAi\Controllers\Controller;
use OtomaticAi\Models\Persona;
use OtomaticAi\Models\SingleModeGeneration;
use OtomaticAi\Utils\Auth;
use OtomaticAi\Utils\Language;
use OtomaticAi\Utils\Scheduler;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class SingleModeController extends Controller
{
    public function index()
    {
        $this->verifyNonce();

        $this->validate([
            "page" => ["nullable", "integer"],
        ]);

        $models = SingleModeGeneration::query()
            ->select(["id", "title", "status", "language", "created_at", "updated_at"])
            ->orderBy("created_at", "desc")
            ->paginate(15, ['*'], 'page', $this->input('page', 1));

        $this->response($models);
    }

    public function latest()
    {
        $this->verifyNonce();

        $this->validate([
            "limit" => ["nullable", "integer", "min:1"],
        ]);

        $projects = SingleModeGeneration::latest()->limit($this->input("limit", 5))->get();

        $this->response($projects);
    }

    public function show()
    {
        $this->verifyNonce();

        $this->validate([
            "id" => ["required", "integer"],
        ]);

        $model = SingleModeGeneration::find($this->input("id"));

        if ($model === null) {
            $this->response(["message" => "An error occurred", "error" => "Unable to find the generation #" . $this->input("id") . "."], 503);
        }

        $this->response($model);
    }

    public function destroy()
    {
        $this->verifyNonce();

        $this->validate([
            "id" => ["required", "integer"],
        ]);

        $model = SingleModeGeneration::find($this->input("id"));

        if ($model === null) {
            $this->response(["message" => "An error occurred", "error" => "Unable to find the generation #" . $this->input("id") . "."], 503);
        }

        $model->delete();

        $this->emptyResponse();
    }

    public function store()
    {
        $this->verifyNonce();

        $validated = $this->validate([
            "type" => ["required", "string"],
            "title" => ["required"],
            "language" => ["required", "string"],
            "meta" => ["nullable", "array"],
            "persona_id" => ["nullable", "integer"],

            // models
            "settings.models.text" => ["required", "string"],
            "settings.models.image" => ["required", "string"],

            // generation brief
            "settings.generation_brief" => ["nullable", "string"],

            // data
            "settings.data.serp.enabled" => ["required", "boolean"],
            "settings.data.links" => ["nullable", "array"],

            // custom instructions
            "settings.custom_instructions.profile" => ["nullable", "string"],
            "settings.custom_instructions.images" => ["nullable", "string"],

            // images
            "settings.images.thumbnail.enabled" => ["required", "boolean"],
            "settings.images.content.enabled" => ["required", "boolean"],
            "settings.images.content.max_images" => ["integer", "min:0"],
            "settings.images.custom_instructions" => ["nullable", "string"],

            // youtube settings
            "settings.youtube.enabled" => ["required", "boolean"],

            // embeds settings
            "settings.embeds.enabled" => ["required", "boolean"],

            // internal links settings
            "settings.internal_links.enabled" => ["required", "boolean"],
            "settings.internal_links.no_follow" => ["required", "boolean"],

            // external links settings
            "settings.external_links.enabled" => ["required", "boolean"],
            "settings.external_links.no_follow" => ["required", "boolean"],

            // custom links settings
            "settings.custom_links.enabled" => ["required", "boolean"],
            "settings.custom_links.links" => ["nullable", "array"],

            // lists settings
            "settings.lists.enabled" => ["required", "boolean"],

            // tables settings
            "settings.tables.enabled" => ["required", "boolean"],

            // toolbox settings
            "settings.toolbox.enabled" => ["required", "boolean"],
            "settings.toolbox.template" => ["string"],

            // bold words settings
            "settings.bold_words.enabled" => ["required", "boolean"],

            // emojis settings
            "settings.emojis.enabled" => ["required", "boolean"],

            // summary settings
            "settings.summary.enabled" => ["required", "boolean"],

            // faq settings
            "settings.faq.enabled" => ["required", "boolean"],

            // others settigns
            "settings.text_length" => ["required", "string"],
            "settings.keywords" => ["nullable", "array"],
            "settings.amazon.enabled" => ["required", "boolean"],
            "settings.amazon.template" => ["string"],
            "settings.amazon.max_products" => ["integer", "min:0"],
            "settings.writing_style" => ["nullable", "string"],
            "settings.profile_custom_instructions" => ["nullable", "string"],
            "settings.seo_title" => ["nullable", "string"],
            "settings.seo_description" => ["nullable", "string"],
        ]);

        // refresh auth
        // Auth::refreshDomain();

        if (!Auth::isPremium()) {
            $this->response(["message" => "An error occurred", "error" => "This feature requires a premium subscription."], 503);
        }

        $model = new SingleModeGeneration([
            "title" => Arr::get($validated, "title"),
            "type" => Arr::get($validated, "type"),
            "language" => Language::find(Arr::get($validated, "language"), "en"),
            "settings" => Arr::get($validated, "settings"),
            "meta" => Arr::get($validated, "meta"),
            "status" => "idle",
        ]);

        if (!empty($this->input("persona_id"))) {
            $persona = Persona::find($this->input("persona_id"));
            if ($persona) {
                $model->persona()->associate($persona);
            }
        }

        if ($model->save()) {
            Scheduler::single("generate_single_mode", [$model->id]);
            $this->response($model);
        }

        $this->response(["message" => "An error occurred", "error" => "Unable to store the generation."], 503);
    }

    public function update()
    {
        $this->verifyNonce();

        $validated = $this->validate([
            "id" => ["required", "integer"],
            "regenerate" => ["boolean"],

            "title" => ["required"],
            "language" => ["required", "string"],
            "persona_id" => ["nullable", "integer"],

            // models
            "settings.models.text" => ["required", "string"],
            "settings.models.image" => ["required", "string"],

            // generation brief
            "settings.generation_brief" => ["nullable", "string"],

            // data
            "settings.data.serp.enabled" => ["required", "boolean"],
            "settings.data.links" => ["nullable", "array"],

            // custom instructions
            "settings.custom_instructions.profile" => ["nullable", "string"],
            "settings.custom_instructions.images" => ["nullable", "string"],

            // images
            "settings.images.thumbnail.enabled" => ["required", "boolean"],
            "settings.images.content.enabled" => ["required", "boolean"],
            "settings.images.content.max_images" => ["integer", "min:0"],

            // youtube settings
            "settings.youtube.enabled" => ["required", "boolean"],

            // embeds settings
            "settings.embeds.enabled" => ["required", "boolean"],

            // internal links settings
            "settings.internal_links.enabled" => ["required", "boolean"],
            "settings.internal_links.no_follow" => ["required", "boolean"],

            // external links settings
            "settings.external_links.enabled" => ["required", "boolean"],
            "settings.external_links.no_follow" => ["required", "boolean"],

            // custom links settings
            "settings.custom_links.enabled" => ["required", "boolean"],
            "settings.custom_links.links" => ["nullable", "array"],

            // lists settings
            "settings.lists.enabled" => ["required", "boolean"],

            // tables settings
            "settings.tables.enabled" => ["required", "boolean"],

            // toolbox settings
            "settings.toolbox.enabled" => ["required", "boolean"],
            "settings.toolbox.template" => ["string"],

            // bold words settings
            "settings.bold_words.enabled" => ["required", "boolean"],

            // emojis settings
            "settings.emojis.enabled" => ["required", "boolean"],

            // summary settings
            "settings.summary.enabled" => ["required", "boolean"],

            // faq settings
            "settings.faq.enabled" => ["required", "boolean"],

            // others settings
            "settings.text_length" => ["required", "string"],
            "settings.keywords" => ["nullable", "array"],
            "settings.amazon.enabled" => ["required", "boolean"],
            "settings.amazon.template" => ["string"],
            "settings.amazon.max_products" => ["integer", "min:0"],
            "settings.writing_style" => ["nullable", "string"],
            "settings.profile_custom_instructions" => ["nullable", "string"],
            "settings.seo_title" => ["nullable", "string"],
            "settings.seo_description" => ["nullable", "string"],
        ]);

        // refresh auth
        // Auth::refreshDomain();

        if (!Auth::isPremium()) {
            $this->response(["message" => "An error occurred", "error" => "This feature requires a premium subscription."], 503);
        }

        $model = SingleModeGeneration::find($this->input("id"));

        if ($model === null) {
            $this->response(["message" => "An error occurred", "error" => "Unable to find the generation #" . $this->input("id") . "."], 503);
        }

        $model->title = Arr::get($validated, "title");
        $model->language = Language::find(Arr::get($validated, "language"), "en");
        $model->settings = Arr::get($validated, "settings", []);

        if (Arr::get($validated, "regenerate", false)) {
            $model->status = "idle";
            $model->logs = [];
        }

        if (!empty($this->input("persona_id")) && !empty($persona = Persona::find($this->input("persona_id")))) {
            $model->persona()->associate($persona);
        } else {
            $model->persona()->dissociate();
        }

        if ($model->save()) {
            if ($this->input("regenerate", false)) {
                Scheduler::single("generate_single_mode", [$model->id]);
            }
            $this->response($model);
        }

        $this->response(["message" => "An error occurred", "error" => "Unable to update the generation."], 503);
    }
}
