<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * Idempotency log for provider webhook deliveries. Stripe + Razorpay both
 * retry deliveries aggressively (any non-2xx response queues a retry within
 * minutes); without a dedup key, a flaky 500 followed by a successful retry
 * would double-process the event and corrupt subscription state.
 *
 * The `(provider_key, provider_event_id)` unique index is THE dedup key —
 * inserts collide on replay, the dispatcher catches the collision and no-ops.
 *
 * `payload` is kept as a debug aid (full event JSON at processing time) and
 * is deliberately `text` not `json`: cheap to store, infrequently queried.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('webhook_events', function (Blueprint $table) {
            $table->id();
            $table->string('provider_key', 32);
            $table->string('provider_event_id', 191);
            $table->string('event_type', 64);
            $table->timestamp('processed_at');
            $table->text('payload')->nullable();
            $table->timestamps();

            $table->unique(['provider_key', 'provider_event_id']);
            $table->index(['provider_key', 'event_type']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('webhook_events');
    }
};
