<?php

namespace App\Jobs;

use App\Mail\SurveyAIInsightsMail;
use App\Models\SurveyResponse;
use App\Services\ClaudeService;
use Illuminate\Support\Facades\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public int $timeout = 120;
    public int $tries = 2;

    public function __construct(public SurveyResponse $survey) {}

    public function handle(ClaudeService $claude): void
    {
        $this->survey->update(['ai_status' => 'processing']);

        $insights = $claude->generateSurveyInsights($this->survey);

        if ($insights === null) {
            $this->survey->update(['ai_status' => 'failed']);
            return;
        }

        $this->survey->update([
            'ai_strategic_diagnosis' => $insights['strategic_diagnosis'] ?? null,
            'ai_customer_narrative'  => $insights['customer_narrative'] ?? null,
            'ai_action_plan_30day'   => $insights['action_plan_30day'] ?? [],
            'ai_content_ideas'       => $insights['content_ideas'] ?? [],
            'ai_brand_voice_sample'  => $insights['brand_voice_sample'] ?? null,
            'ai_status'              => 'completed',
            'ai_generated_at'        => now(),
        ]);

        // AI insights бэлэн боллоо — email явуулах
        if ($this->survey->lead) {
            try {
                Mail::to($this->survey->lead->email)->queue(new SurveyAIInsightsMail($this->survey->lead, $this->survey));
            } catch (\Exception $e) {
                \Log::warning('Failed to queue AI insights email: ' . $e->getMessage());
            }
        }
    }

    public function failed(\Throwable $e): void
    {
        $this->survey->update(['ai_status' => 'failed']);
    }
}
