<?php

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

/**
 * A grant is an order without money, not a second code path — so a subscription
 * given away for free or at a discount is a row in this same table, with
 * `stripe_subscription_id` null and `price_cents` set to what the customer
 * actually pays. What makes it a grant rather than a bug is provenance: who
 * gave it, when, why (free text), and until when.
 *
 * `catalogue_price_cents` sits beside `price_cents` for exactly one reason: a
 * discount is only legible as a discount if the price it was discounted FROM
 * is on the same row. Left null for an ordinary paid subscription, where
 * `price_cents` already IS the catalogue price at the time of sale.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            // Nullable and nullOnDelete: an operator leaving the company must
            // not take the record of what they gave away with them — the grant
            // itself outlives its own audit trail either way.
            $table->foreignId('granted_by')->nullable()->after('cancelled_at')
                ->constrained('operators')->nullOnDelete();
            // The presence of this column, not a separate boolean, is what
            // marks a subscription as a grant — one fact, one column.
            $table->timestamp('granted_at')->nullable()->after('granted_by');
            $table->text('grant_note')->nullable()->after('granted_at');
            // Null means unlimited. The owner's rule: nothing lapses on its
            // own when this date passes — the console only has to say so.
            $table->timestamp('granted_until')->nullable()->after('grant_note');
            $table->unsignedInteger('catalogue_price_cents')->nullable()->after('granted_until');
        });
    }

    public function down(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->dropConstrainedForeignId('granted_by');
            $table->dropColumn(['granted_at', 'grant_note', 'granted_until', 'catalogue_price_cents']);
        });
    }
};
