<?php

namespace App\Jobs;

use App\Models\Creation;
use App\Models\Translation;
use App\Services\AiProviderService;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class TranslateCreationJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(private readonly Creation $creation) {}

    public function handle(AiProviderService $aiProviderService): void
    {
        $frenchName = $this->creation->nameTranslationKey->getTranslation('fr');
        $frenchShortDesc = $this->creation->shortDescriptionTranslationKey->getTranslation('fr');
        $frenchDesc = $this->creation->descriptionTranslationKey->getTranslation('fr');

        $shortDescriptionTranslationKeyId = $this->creation->shortDescriptionTranslationKey->id;
        $descriptionTranslationKeyId = $this->creation->descriptionTranslationKey->id;

        if (! empty($frenchName)) {
            Translation::updateOrCreate(
                ['translation_key_id' => $this->creation->name_translation_key_id, 'locale' => 'en'],
                ['text' => $frenchName]
            );
            Cache::forget("translation_key_{$this->creation->name_translation_key_id}_en");
        }

        if (! empty($frenchShortDesc)) {
            Translation::updateOrCreate(
                ['translation_key_id' => $shortDescriptionTranslationKeyId, 'locale' => 'en'],
                ['text' => $this->translate($frenchShortDesc, $aiProviderService)]
            );
            Cache::forget("translation_key_{$shortDescriptionTranslationKeyId}_en");
        }

        if (! empty($frenchDesc)) {
            Translation::updateOrCreate(
                ['translation_key_id' => $descriptionTranslationKeyId, 'locale' => 'en'],
                ['text' => $this->translate($frenchDesc, $aiProviderService)]
            );
            Cache::forget("translation_key_{$descriptionTranslationKeyId}_en");
        }
    }

    /**
     * Translate the given text from French to English
     *
     * @param  string  $text  The text to translate
     * @param  AiProviderService  $aiProviderService  The AI provider service
     * @return string The translated text
     */
    private function translate(string $text, AiProviderService $aiProviderService): string
    {
        try {
            $result = $aiProviderService->prompt(
                'You are a helpful assistant that translates french markdown text in english and that outputs JSON in the format {message:string}. Markdown is supported.',
                $text
            );

            return $result['message'] ?? '';
        } catch (Exception $e) {
            Log::error("Failed to translate text: {$text}", [
                'exception' => $e->getMessage(),
            ]);
        }

        return '';
    }
}