<?php

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

/**
 * Subscriptions + invoices need to survive a user-delete for accounting and
 * tax-window purposes. Two changes:
 *
 *   1. Flip `subscriptions.user_id` from `cascadeOnDelete` to `nullOnDelete`
 *      so a user purge orphans the row instead of nuking it. Invoices are
 *      already `restrictOnDelete` on subscriptions, so once subscriptions
 *      survive, the invoice chain follows.
 *   2. Add `user_email_snapshot` so the admin Subscriptions / Invoices
 *      pages can still show "Pro · 7.50 · alice@example.com (deleted)"
 *      after the user row is gone. UsersController::purgeUser populates it
 *      at delete time.
 *
 * `provider_customers.user_id` stays cascading — it's an internal lookup
 * (our id ↔ Stripe customer id), not historical record. Stripe keeps the
 * customer record on its side, so we don't need our own copy after delete.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
            $table->unsignedBigInteger('user_id')->nullable()->change();
            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->nullOnDelete();
            $table->string('user_email_snapshot', 191)->nullable()->after('user_id');
        });
    }

    public function down(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->dropColumn('user_email_snapshot');
            $table->dropForeign(['user_id']);
            $table->unsignedBigInteger('user_id')->nullable(false)->change();
            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->cascadeOnDelete();
        });
    }
};
