<?php

namespace Modules\WhatsApp\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Modules\WhatsApp\Entities\Services\ConversationService;
use Modules\WhatsApp\Entities\Services\InboundPipeline;
use Modules\WhatsApp\Entities\WaConversation;
use Modules\WhatsApp\Entities\WaMessage;

/**
 * Runs the AI auto-reply pipeline for one inbound message. Queued so the slow
 * LLM call never blocks the webhook / bridge. (Requires a queue worker — AI
 * auto-reply is an opt-in advanced feature.)
 */
class ProcessInboundMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $messageId;
    public int $tries = 1;
    public int $timeout = 120;

    public function __construct(int $messageId)
    {
        $this->messageId = $messageId;
    }

    public function handle(): void
    {
        $message = WaMessage::find($this->messageId);
        if (!$message || $message->direction !== 'in') {
            return;
        }

        $conversation = $message->conversation_id
            ? WaConversation::find($message->conversation_id)
            : (new ConversationService())->recordMessage($message);

        if (!$conversation) {
            return;
        }

        (new InboundPipeline())->process($message, $conversation);
    }
}
