<?php

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

/**
 * What Stripe needs before a plan change can reach it.
 *
 * A subscription is not billed at a price directly: it is billed through an
 * ITEM, and moving a contract onto another package means swapping the price on
 * that item. Only the subscription id was ever stored, so there was no handle to
 * swap anything with — a customer who upgraded went on being charged for the
 * package they had left, every month, for as long as the contract ran.
 *
 * `stripe_item_id` is that handle. It is filled from whatever tells us first:
 * a `customer.subscription.updated` event carries it, and a contract that
 * predates this column is asked about at Stripe the moment a change needs it
 * (see App\Actions\MoveStripeSubscriptionPrice). The item id survives a price
 * swap, so it is learnt once and kept.
 *
 * `stripe_price_id` is what Stripe is billing as far as we know, and
 * `stripe_price_sync` is the swap that has NOT reached them: the price it was
 * meant to move to, the proration behaviour that was chosen for its direction,
 * the error, and how often it has been tried. A change is applied to the machine
 * and to the contract before Stripe is told, and it must not be rolled back
 * because Stripe was unreachable — so the part that failed is parked here, where
 * clupilot:sync-stripe-subscriptions picks it up again and where an operator can
 * see money that is still being taken at the old rate.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->string('stripe_item_id')->nullable()->after('stripe_subscription_id');
            $table->string('stripe_price_id')->nullable()->after('stripe_item_id');
            $table->timestamp('stripe_price_synced_at')->nullable()->after('stripe_price_id');
            $table->json('stripe_price_sync')->nullable()->after('stripe_price_synced_at');
        });
    }

    public function down(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->dropColumn([
                'stripe_item_id', 'stripe_price_id', 'stripe_price_synced_at', 'stripe_price_sync',
            ]);
        });
    }
};
