<?php

declare(strict_types=1);

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('subscriptions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();

            // Restrict: a plan with live subscribers must not be deletable.
            $table->foreignId('plan_id')->constrained()->restrictOnDelete();

            $table->enum('status', ['incomplete', 'trialing', 'active', 'past_due', 'canceled', 'expired'])
                ->default('incomplete');

            // Provider-agnostic: the payment gateway is pluggable.
            $table->string('provider', 64)->nullable();
            $table->string('provider_subscription_id')->nullable();

            $table->timestamp('current_period_start')->nullable();
            $table->timestamp('current_period_end')->nullable();
            $table->timestamp('trial_ends_at')->nullable();
            $table->timestamp('canceled_at')->nullable();
            $table->timestamp('ends_at')->nullable();

            $table->json('metadata')->nullable();

            $table->timestamps();
            $table->softDeletes();

            /*
             * At most one entitling subscription per account, enforced by the
             * database rather than by hope.
             *
             * `active_marker` is set to the user id while the subscription grants
             * entitlements and NULL otherwise, so the unique index binds only the
             * live row -- MySQL treats NULLs as distinct, which is exactly the
             * behaviour wanted here. Without it, a retried checkout or a
             * duplicated webhook could leave an account holding two plans, and
             * the fee resolver would pick whichever it happened to read first.
             *
             * Maintained by the model, so the invariant cannot be sidestepped by
             * writing through a different code path.
             */
            $table->unsignedBigInteger('active_marker')->nullable();
            $table->unique('active_marker');

            $table->index(['user_id', 'status']);
            $table->index(['provider', 'provider_subscription_id']);
            $table->index('current_period_end');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('subscriptions');
    }
};
