<?php

declare(strict_types=1);

namespace ImovelZapAi\Importing\Application\Actions;

use ImovelZapAi\Importing\Application\Services\ImportLogWriter;
use ImovelZapAi\Importing\Domain\Enums\ImportJobStatus;
use ImovelZapAi\Importing\Domain\Enums\ImportLogEvent;
use ImovelZapAi\Importing\Domain\Exceptions\ImportException;
use ImovelZapAi\Importing\Infrastructure\Jobs\ExecuteImportJob;
use ImovelZapAi\Importing\Infrastructure\Persistence\Eloquent\ImportJobModel;

final class RetryImportAction
{
    public function __construct(
        private readonly ImportLogWriter $logWriter,
    ) {}

    public function execute(ImportJobModel $job): ImportJobModel
    {
        $status = $job->status instanceof ImportJobStatus
            ? $job->status
            : ImportJobStatus::from((string) $job->status);

        if (! $status->canRetry()) {
            throw ImportException::invalidState($status->value, 'retry');
        }

        $job->forceFill([
            'status' => ImportJobStatus::Queued,
            'queued_at' => now(),
            'failure_message' => null,
            'completed_at' => null,
        ])->save();

        $this->logWriter->write(
            $job->tenant_id,
            $job->id,
            ImportLogEvent::RetryStarted,
            message: 'Retry iniciado a partir do checkpoint.',
            context: ['checkpoint_index' => $job->checkpoint_index],
        );

        ExecuteImportJob::dispatch($job->id, $job->tenant_id)
            ->onQueue((string) config('importing.queue', 'imports'));

        return $job->fresh();
    }
}
