<?php

namespace OtomaticAi\Controllers\SingleMode;

use Exception;
use OtomaticAi\Controllers\Controller;
use OtomaticAi\Models\Presets\Preset;
use OtomaticAi\Utils\Language;
use OtomaticAi\Vendors\Illuminate\Support\Arr;
use OtomaticAi\Vendors\Illuminate\Support\Str;

class SeoController extends Controller
{
    public function generateTitle()
    {
        $this->validate([
            "title" => ["required", "string"],
            "language" => ["required", "string"],
        ]);

        try {
            // get the openai preset
            $preset = Preset::findFromAPI('generate_seo_title');

            // run the preset
            $response = $preset->process([
                "language" => Language::find($this->input('language', 'en'))->value,
                "request" => $this->input('title'),
                "has_emojis" => false,
            ]);

            // get the response content
            $response = json_decode(Arr::get($response, 'choices.0.message.content'), true, 512, JSON_THROW_ON_ERROR);
            $content = Arr::get($response, "value");
            $content = Str::clean($content);

            $this->response([
                "title" => $content,
            ]);
        } catch (Exception $e) {
            $this->response(["message" => "An error occurred", "error" => $e->getMessage()], 503);
        }
    }

    public function generateDescription()
    {
        $this->validate([
            "title" => ["required", "string"],
            "language" => ["required", "string"],
        ]);

        try {
            // get the openai preset
            $preset = Preset::findFromAPI('generate_seo_description');

            // run the preset
            $response = $preset->process([
                "language" => Language::find($this->input('language', 'en'))->value,
                "request" => $this->input('title'),
            ]);

            // get the response content
            $response = json_decode(Arr::get($response, 'choices.0.message.content'), true, 512, JSON_THROW_ON_ERROR);
            $content = Arr::get($response, "value");
            $content = Str::clean($content);

            $this->response([
                "description" => $content,
            ]);
        } catch (Exception $e) {
            $this->response(["message" => "An error occurred", "error" => $e->getMessage()], 503);
        }
    }
}
