<?php

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

/**
 * The handle Stripe's webhooks arrive with.
 *
 * From here on Stripe owns the billing cycle: it decides when a renewal is
 * paid, when it has failed, and when a subscription has ended. Every one of
 * those events names a Stripe subscription and nothing else — so without this
 * column an `invoice.paid` cannot be matched to the contract it renews.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            // Unique: one Stripe subscription bills exactly one contract, and a
            // second row claiming the same id would make every webhook
            // ambiguous.
            $table->string('stripe_subscription_id')->nullable()->unique()->after('order_id');
            // Stripe's own view of the state (active, past_due, canceled …),
            // kept beside ours: they are the authority on whether the money
            // arrived, we are the authority on what the customer may use.
            $table->string('stripe_status')->nullable()->after('status');
        });

        Schema::table('orders', function (Blueprint $table) {
            $table->string('stripe_subscription_id')->nullable()->after('stripe_event_id');
        });
    }

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

        Schema::table('orders', function (Blueprint $table) {
            $table->dropColumn('stripe_subscription_id');
        });
    }
};
