<?php

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

/**
 * One entry per thing that happened.
 *
 * Stripe retries a webhook until it gets a 2xx, and can deliver the same one
 * twice at once. Checking for an existing row and inserting afterwards leaves a
 * window both deliveries walk through — and a register that counts a payment
 * twice is worse than one that is late.
 *
 * A single nullable key rather than a composite of columns, because what
 * identifies "the same event" differs by kind: a renewal is its invoice, a
 * cancellation is its subscription. Events that need no such protection leave
 * it null, and NULLs do not collide.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('subscription_records', function (Blueprint $table) {
            $table->string('event_key')->nullable()->unique()->after('event');
        });
    }

    public function down(): void
    {
        Schema::table('subscription_records', function (Blueprint $table) {
            $table->dropUnique(['event_key']);
            $table->dropColumn('event_key');
        });
    }
};
