<?php

namespace App\Jobs;

use App\Models\Company;
use App\Services\Sefaz\DistribuicaoDfeService;
use App\Services\Sefaz\ManifestacaoService;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class SincronizarEmpresaJob implements ShouldBeUnique, ShouldQueue
{
    use Queueable;

    public int $tries = 1;

    public int $timeout = 600;

    public function __construct(
        public int $companyId,
        public string $origem = 'cron',
    ) {}

    public function uniqueId(): string
    {
        return (string) $this->companyId;
    }

    public function handle(DistribuicaoDfeService $dfe, ManifestacaoService $manifestacao): void
    {
        $company = Company::find($this->companyId);

        if (! $company || ! $company->hasCertificate()) {
            return;
        }

        $log = $dfe->sync($company, $this->origem);

        // Bloqueio por consumo indevido: recua a próxima tentativa em 1 hora
        // sobre o intervalo já configurado, evitando insistir no erro.
        if ($log->cstat === '656') {
            $company->forceFill(['last_sync_at' => now()->addHour()])->save();

            return;
        }

        if ($company->manifestacao_automatica) {
            $manifestacao->darCienciaPendentes($company->fresh());
        }
    }
}
