<?php

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

/**
 * Records WHICH version a contract was sold under.
 *
 * The plan key is not enough and never was: "team" in 2026 and "team" in 2029
 * are different promises. A historical reference resolved by family key would
 * hand back today's terms, which is the same mistake the snapshot exists to
 * prevent — one level up. So every contract points at the exact version.
 *
 * The snapshot on the subscription stays authoritative for what the customer is
 * owed; this is the provenance, not a lookup to read terms through.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            $table->foreignId('plan_version_id')->nullable()->after('plan')
                ->constrained()->nullOnDelete();
        });

        // Existing contracts were sold under version 1 — the only version there
        // has ever been, seeded from the catalogue they were sold from.
        $versions = DB::table('plan_versions')
            ->join('plan_families', 'plan_families.id', '=', 'plan_versions.plan_family_id')
            ->where('plan_versions.version', 1)
            ->pluck('plan_versions.id', 'plan_families.key');

        foreach ($versions as $key => $versionId) {
            DB::table('subscriptions')
                ->whereNull('plan_version_id')
                ->where('plan', $key)
                ->update(['plan_version_id' => $versionId]);
        }
    }

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