<?php

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

/**
 * When the newest Stripe event we have applied to this contract was raised.
 *
 * Stripe does not guarantee delivery order. Without this, a renewal delayed in
 * the network and delivered after the next one moves the period BACKWARD and
 * can make a paid-up contract look expired; a failed-attempt event delivered
 * after the successful retry flips a healthy subscription back to past_due.
 *
 * The register does not need this — each entry is keyed by what it is about, so
 * a late arrival is still recorded once, in its proper place. It is only the
 * mutable state that has to refuse to go backwards.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->timestamp('stripe_event_at')->nullable()->after('stripe_status');
            // Stripe's timestamps have one-second resolution, and a failed
            // attempt and its successful retry can share a second. The rank
            // breaks that tie by what the event says about the money: a
            // payment that succeeded outranks one that did not.
            $table->unsignedTinyInteger('stripe_event_rank')->nullable()->after('stripe_event_at');
        });
    }

    public function down(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->dropColumn(['stripe_event_at', 'stripe_event_rank']);
        });
    }
};
