<?php

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

/**
 * What it takes to let Stripe bill a module every month instead of once.
 *
 * A booked module was a row in `subscription_addons` and a line on the first
 * invoice, and nothing on the Stripe subscription at all — so the month it was
 * booked in was the only month it was ever charged for. Everything here exists
 * to close that: the Prices modules are sold at, the item each booking bills
 * through, and the appointment a cancellation makes.
 */
return new class extends Migration
{
    public function up(): void
    {
        /**
         * The Stripe Price a module is sold at, per amount and per interval.
         *
         * Not one Price per module: a booking is frozen at the price it was
         * booked at, so a customer who took storage at ten euros keeps paying
         * ten after the catalogue moves to twelve — and a Stripe Price is
         * immutable, so those are two different Prices that both have to stay
         * live. The interval is part of the key for the same reason it is on the
         * plan side: a Stripe Price carries its own recurring interval, and
         * every item on one subscription has to share it, so a module on a
         * yearly contract is a yearly Price of twelve times the monthly figure.
         *
         * Amounts are NET, exactly like `plan_prices` — what is actually charged
         * depends on the customer's tax treatment, which is ours to work out and
         * not Stripe's.
         */
        Schema::create('stripe_addon_prices', function (Blueprint $table) {
            $table->id();
            $table->string('addon_key');
            $table->unsignedInteger('amount_cents');
            $table->char('currency', 3);
            $table->string('interval');
            $table->string('stripe_product_id');
            $table->string('stripe_price_id');
            $table->timestamps();

            // The identity of a Price. Two rows for one combination would leave
            // two live Stripe Prices for the same module at the same money, and
            // no way to tell which a customer is billed on.
            $table->unique(['addon_key', 'amount_cents', 'currency', 'interval'], 'stripe_addon_prices_unique');
        });

        Schema::table('subscription_addons', function (Blueprint $table) {
            // The subscription item this booking bills through. Several
            // bookings of one module at one price share a single item with a
            // quantity — that is what "sold in packs" means to Stripe — so the
            // id is stamped on every row of the group.
            $table->string('stripe_item_id')->nullable()->after('quantity');
            $table->string('stripe_price_id')->nullable()->after('stripe_item_id');

            // The appointment a cancellation makes, separate from
            // `cancelled_at`, which says the module has actually stopped. A
            // cancellation is monthly and takes effect at the end of the term
            // the customer has already paid for: until this date passes they
            // keep the module, and afterwards clupilot:end-cancelled-addons
            // sets `cancelled_at` and the entitlement goes.
            $table->timestamp('cancels_at')->nullable()->after('cancelled_at');

            $table->index('stripe_item_id');
            // Read by the sweep that ends modules whose term has run out.
            $table->index(['cancels_at', 'cancelled_at']);
        });

        Schema::table('subscriptions', function (Blueprint $table) {
            // The module items that never reached Stripe, in the same shape and
            // for the same reason as `stripe_price_sync` beside it: a booking is
            // delivered to the machine before Stripe is told, and it is not
            // rolled back when Stripe is away, so what is left is a customer
            // holding a module nobody is billing them for.
            //
            // Its own column rather than sharing that one: a plan swap and a
            // module item are two different outstanding pieces of work, and
            // clearing one on success would silently drop the other.
            $table->json('stripe_addon_sync')->nullable()->after('stripe_price_sync');
        });
    }

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

        Schema::table('subscription_addons', function (Blueprint $table) {
            $table->dropIndex(['cancels_at', 'cancelled_at']);
            $table->dropIndex(['stripe_item_id']);
            $table->dropColumn(['stripe_item_id', 'stripe_price_id', 'cancels_at']);
        });

        Schema::dropIfExists('stripe_addon_prices');
    }
};
