<?php

namespace App\Jobs;

use App\Models\WebhookLog;
use App\Services\CronLogService;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class RetryFailedWebhooksJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(public readonly ?string $gateway = null)
    {
    }

    public function handle(CronLogService $cronLogService): void
    {
        $runKey = 'webhook-retry-'.($this->gateway ?: 'all').'-'.now()->format('YmdHis');
        $log = $cronLogService->start('retry-failed-webhooks', $runKey, ['gateway' => $this->gateway]);

        try {
            $query = WebhookLog::query()->where('status', 'failed');
            if ($this->gateway !== null) {
                $query->where('gateway', $this->gateway);
            }

            $query->chunkById(200, function ($rows): void {
                foreach ($rows as $row) {
                    $row->status = 'received';
                    $row->error_message = null;
                    $row->save();
                }
            });

            $cronLogService->finish($log, 'success', 'Failed webhooks marked for retry processing.');
        } catch (Exception $exception) {
            $cronLogService->finish($log, 'failed', null, $exception->getMessage());
            throw $exception;
        }
    }
}
