<?php

namespace App\Jobs;

use App\Models\Message;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public int $tries = 3;
    public int $timeout = 30;

    public function __construct(public readonly int $messageId) {}

    public function handle(): void
    {
        $message = Message::with(['sender:id,username', 'attachments'])->find($this->messageId);

        if (! $message) {
            return;
        }

        if (! $message->shouldBeSearchable()) {
            $message->unsearchable();
            return;
        }

        $message->searchable();
    }
}
