<?php

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

/**
 * Plan ↔ provider price-id mapping. `provider_key` is a string reference
 * to `payment_providers.key` rather than a hard FK because providers can
 * be deactivated (or temporarily removed from the active set) without
 * losing the historical price-id mapping that older subscriptions still
 * rely on. `(provider_key, period)` is indexed so a webhook handler can
 * resolve "which plan does this Stripe price_xxx belong to?" cheaply.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('plan_provider_links', function (Blueprint $table) {
            $table->id();
            $table->foreignId('plan_id')->constrained('plans')->cascadeOnDelete();
            $table->string('provider_key', 32);
            $table->string('period', 8);
            $table->string('provider_price_id', 191);
            $table->boolean('is_active')->default(true);
            $table->timestamps();

            $table->unique(['plan_id', 'provider_key', 'period']);
            $table->index(['provider_key', 'period']);
        });
    }

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