<?php

namespace App\Modules\Integrations\Platform\Services;

use App\Modules\Integrations\Platform\Models\IntegrationWebhook;
use Illuminate\Support\Carbon;

final class WebhookStatsUpdater
{
    public function onDelivered(IntegrationWebhook $webhook): void
    {
        $webhook->forceFill([
            'health_status' => 'healthy',
            'last_success_at' => Carbon::now(),
            'failure_count' => 0,
        ])->save();
    }

    public function onDeliveryFailure(IntegrationWebhook $webhook, bool $deadLettered): void
    {
        $failures = (int) $webhook->failure_count + 1;
        $webhook->forceFill([
            'last_failure_at' => Carbon::now(),
            'failure_count' => $failures,
            'health_status' => $deadLettered || $failures >= 5 ? 'failing' : 'degraded',
        ])->save();
    }
}
