<?php

namespace App\Jobs;

use App\Services\AdapterRunReconciler;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;
use Throwable;

class ReconcileAdapterRunsJob implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new job instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        try {
            /** @var AdapterRunReconciler $reconciler */
            $reconciler = app(AdapterRunReconciler::class);

            $result = $reconciler->reconcile([
                'older_than_minutes' => 60,
                'limit' => 50,
                'dry_run' => false,
            ]);

            Log::info('ReconcileAdapterRunsJob completed', [
                'candidates' => (int) ($result['candidates'] ?? 0),
                'reconciled' => (int) ($result['reconciled'] ?? 0),
                'skipped' => (int) ($result['skipped'] ?? 0),
            ]);
        } catch (Throwable $e) {
            Log::warning('ReconcileAdapterRunsJob failed', [
                'error' => $e->getMessage(),
            ]);

            throw $e;
        }
    }
}
