<?php

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

/**
 * Products that come bundled with a training programme.
 *
 * `products.is_essential` already exists but is a global flag — "every player
 * everywhere should own this". That cannot express "a player in فرق must own a
 * registration card, but an academy-hour player need not". This pivot does.
 *
 * is_required = true means enrolment in the programme is not complete until the
 * product is bought, and the group view flags anyone missing it.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('program_products')) {
            return;
        }

        Schema::create('program_products', function (Blueprint $table) {
            $table->id();
            $table->foreignId('academy_id')->constrained('academies')->cascadeOnDelete();
            $table->foreignId('training_program_id')->constrained('training_programs')->cascadeOnDelete();
            $table->foreignId('product_id')->constrained('products')->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', 'product_id'], 'program_products_unique');
            $table->index(['training_program_id', 'is_required']);
        });
    }

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