<?php

namespace App\Modules\Integrations\Platform\Services;

use App\Modules\Integrations\Platform\Jobs\DeliverWebhookJob;
use App\Modules\Integrations\Platform\Models\IntegrationWebhookDelivery;

final class WebhookDeliveryRetryService
{
    public function retryDeadLetters(int $limit): int
    {
        $ids = IntegrationWebhookDelivery::query()
            ->where('status', 'dead_letter')
            ->orderBy('id')
            ->limit($limit)
            ->pluck('id');

        $n = 0;
        foreach ($ids as $id) {
            $delivery = IntegrationWebhookDelivery::query()->whereKey($id)->first();
            if (! $delivery instanceof IntegrationWebhookDelivery) {
                continue;
            }
            $delivery->forceFill([
                'status' => 'pending',
                'attempt' => 0,
                'attempt_count' => 0,
                'dead_lettered_at' => null,
                'exhausted_at' => null,
                'delivered_at' => null,
                'error' => null,
                'next_retry_at' => null,
                'response_status' => null,
                'response_body' => null,
            ])->save();
            DeliverWebhookJob::dispatch((int) $delivery->id);
            $n++;
        }

        return $n;
    }
}
