<?php

declare(strict_types=1);

namespace ImovelZapAi\Owners\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\Owners\Application\Actions\RunOwnerAlertsAction;
use ImovelZapAi\Tenancy\Infrastructure\Persistence\Eloquent\TenantModel;
use ImovelZapAi\Tenancy\Support\TenantContext;

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

    public int $tries = 1;

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

    public function handle(RunOwnerAlertsAction $action): void
    {
        TenantModel::query()->orderBy('id')->limit(200)->get()->each(function (TenantModel $tenant) use ($action): void {
            TenantContext::clear();
            TenantContext::set((string) $tenant->id);
            try {
                $action->execute((string) $tenant->id);
            } finally {
                TenantContext::clear();
            }
        });
    }
}
