<?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\Visits\Domain\Enums\VisitReminderStatus;
use ImovelZapAi\Visits\Infrastructure\Persistence\Eloquent\VisitReminderModel;

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

    public int $tries = 1;

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

    public function handle(): void
    {
        VisitReminderModel::query()
            ->where('status', VisitReminderStatus::Pending)
            ->where('scheduled_for', '<=', now())
            ->orderBy('scheduled_for')
            ->limit(100)
            ->get()
            ->each(function (VisitReminderModel $reminder): void {
                SendVisitReminderJob::dispatch($reminder->id, $reminder->tenant_id)
                    ->onQueue((string) config('visits.queue', 'visits'));
            });
    }
}
