<?php

namespace App\Jobs\Synapse;

use App\Enum\Contact\MessageDirection;
use App\Models\Contact\Hub\ContactMessage;
use App\Synapse\Agents\EmailClassifierAgent;
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\Log;

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

    public int $tries   = 2;
    public int $timeout = 60;
    public int $backoff = 15;

    public function __construct(
        public readonly int $messageId,
        public readonly bool $force = false,
    ) {}

    public function handle(): void
    {
        $message = ContactMessage::find($this->messageId);

        if (!$message) {
            Log::warning("ClassifyInboundEmailJob: message {$this->messageId} not found.");
            return;
        }

        if ($message->direction !== MessageDirection::INBOUND) {
            Log::warning("ClassifyInboundEmailJob: message {$this->messageId} is not inbound — skipping.");
            return;
        }

        if (!$this->force && $message->classification_status === 'completed') {
            Log::info("ClassifyInboundEmailJob: message {$this->messageId} already classified — skipping.");
            return;
        }

        $message->update(['classification_status' => 'processing']);

        try {
            $prompt = $message->aiPrompt();

            $result = (new EmailClassifierAgent)->prompt($prompt);

            $message->update([
                'classification'            => $result['classification'] ?? null,
                'classification_status'     => 'completed',
                'classification_confidence' => $result['confidence'] ?? null,
                'classification_notes'      => $result['reasoning'] ?? null,
            ]);

            Log::info("ClassifyInboundEmailJob: message {$this->messageId} classified as '{$result['classification']}' ({$result['confidence']}).");

            if (($result['classification'] ?? null) === 'dsar_response') {
                FindRelatedDsarJob::dispatch($this->messageId);
            }

        } catch (\Throwable $e) {
            $message->update(['classification_status' => 'failed']);

            Log::error("ClassifyInboundEmailJob: failed for message {$this->messageId}.", [
                'error' => $e->getMessage(),
            ]);

            report($e);
            $this->fail($e);
        }
    }
}
