<?php

declare(strict_types=1);

namespace ImovelZapAi\Visits\Infrastructure\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use ImovelZapAi\Tenancy\Support\TenantContext;
use ImovelZapAi\Visits\Application\Actions\SendVisitReminderAction;

final class SendVisitReminderJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public int $tries = 3;

    /** @var list<int> */
    public array $backoff = [30, 60, 120];

    public int $timeout = 60;

    public function __construct(
        public readonly string $reminderId,
        public readonly string $tenantId,
    ) {
        $this->onQueue((string) config('visits.queue', 'visits'));
    }

    public function handle(SendVisitReminderAction $action): void
    {
        TenantContext::clear();
        TenantContext::set($this->tenantId);

        try {
            $action->execute($this->reminderId, $this->tenantId);
        } finally {
            TenantContext::clear();
        }
    }
}
