<?php

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

/**
 * Kits that come bundled with a training programme — the same obligation
 * program_products records, for a set sold as one thing.
 *
 * A separate table rather than a nullable kit_id on program_products: that
 * pivot's product_id is NOT NULL and its uniqueness is (academy, programme,
 * product), so a kit row would have to break both.
 *
 * Nor is a kit expanded into its component products. A kit is sold through the
 * POS as a kit — the invoice line carries itemable_type = Kit — so a programme
 * that required the components instead would report every buyer as missing all
 * of them.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('program_kits')) {
            return;
        }

        Schema::create('program_kits', function (Blueprint $table) {
            $table->id();
            $table->foreignId('academy_id')->constrained('academies')->cascadeOnDelete();
            $table->foreignId('training_program_id')->constrained('training_programs')->cascadeOnDelete();
            $table->foreignId('kit_id')->constrained('kits')->cascadeOnDelete();
            $table->boolean('is_required')->default(true);
            $table->unsignedInteger('quantity')->default(1);
            $table->timestamps();

            // Tenant-scoped uniqueness, per the academy_id rule.
            $table->unique(['academy_id', 'training_program_id', 'kit_id'], 'program_kits_unique');
            $table->index(['training_program_id', 'is_required']);
        });
    }

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