<?php

namespace App\Console\Commands;

use App\Jobs\PollSerpCheck;
use App\Models\SerpCheck;
use App\Serp\Operations\OperationAuditLogger;
use Illuminate\Console\Command;

class ReconcileSerpChecksCommand extends Command
{
    protected $signature = 'serp:reconcile {--execute : Düzeltmeleri uygula}';

    protected $description = 'Takılı SERP kontrollerini güvenli biçimde uzlaştırır';

    public function handle(OperationAuditLogger $audit): int
    {
        $count = 0;
        SerpCheck::query()->whereIn('status', ['pending', 'running'])->where('updated_at', '<', now()->subMinutes((int) config('serp.stuck_after_minutes')))->chunkById(100, function ($checks) use (&$count, $audit) {
            foreach ($checks as $c) {
                $count++;
                if (! $this->option('execute')) {
                    continue;
                }if ($c->execution_mode === 'standard' && $c->provider_reference) {
                    PollSerpCheck::dispatch($c->ulid)->onQueue(config('serp.queue'));
                    $audit->record('reconciliation_dispatched', ['check_ulid' => $c->ulid, 'mode' => 'standard']);
                } elseif (! $c->provider_reference) {
                    $c->fail('stuck_without_task', 'SERP kontrolü zamanında tamamlanamadı.');
                    $audit->record('reconciliation_failed_stuck', ['check_ulid' => $c->ulid, 'error_category' => 'poll_exhausted']);
                }
            }
        });
        $this->info(($this->option('execute') ? 'İşlenen' : 'Bulunan').' kayıt: '.$count);

        return self::SUCCESS;
    }
}
