<?php

namespace OtomaticAi\Controllers;

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

class AnalyseLogsController extends Controller
{
    public function __invoke()
    {
        $this->verifyNonce();

        $this->validate([
            "logs" => ["required", "array"],
            "language" => ["required", "string"],
        ]);

        try {
            // get the openai preset
            $preset = Preset::findFromAPI("analyse_publication_logs");

            // make payload
            $payload = [
                "logs" => json_encode($this->input('logs')),
                "language" => Language::find($this->input('language', 'en'))->value,
            ];

            // run the preset
            $response = $preset->process($payload);

            // get the response content
            $response = Arr::get($response, 'choices.0.message.content');

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