<?php

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

/**
 * The questions a product cannot be sold without answering.
 *
 * A kit shirt has a size, a tracksuit has a colour, a printed jersey has a name
 * on the back. None of that is a separate product — it is the same product with
 * a detail the desk has to capture at the moment of sale, because nobody can
 * reconstruct it afterwards from an invoice line that says "قميص تدريب".
 *
 * Two shapes cover every case we have:
 *   text   — the desk types the answer (a name, a note)
 *   select — the admin fixed the answers in advance and the desk picks one
 *            (sizes, colours, anything enumerable)
 *
 * `options` is only meaningful for `select`. It holds a flat list of strings in
 * display order — the values are what gets printed on the invoice item and on
 * the delivery sheet, so they are stored exactly as the admin typed them.
 *
 * The answers do NOT live here. They are frozen onto invoice_items.metadata at
 * sale time, for the same reason invoice prices freeze: renaming "لارج" to "L"
 * next season must not rewrite what a player ordered last season.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('product_customizations')) {
            return;
        }

        Schema::create('product_customizations', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained()->cascadeOnDelete();
            $table->foreignId('product_id')->constrained()->cascadeOnDelete();
            $table->string('name_ar');
            $table->string('name')->nullable();
            $table->string('type', 20)->default('text');
            $table->jsonb('options')->default('[]');
            $table->boolean('is_required')->default(true);
            $table->boolean('is_active')->default(true);
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->timestamps();

            // Tenant-scoped uniqueness, per the academy_id rule: one product
            // cannot ask the same question twice.
            $table->unique(['academy_id', 'product_id', 'name_ar'], 'product_customizations_unique');
            $table->index(['product_id', 'is_active', 'sort_order']);
        });

        DB::statement("ALTER TABLE product_customizations ADD CONSTRAINT product_customizations_type_check CHECK (type IN ('text', 'select'))");
    }

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