<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('product_inventory_variants', function (Blueprint $table) {
            $table->id();

            // anchors
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('shop_id')->constrained()->cascadeOnDelete();
            $table->foreignId('product_inventory_id')->constrained('product_inventories')->cascadeOnDelete();

            // unified combination
            $table->json('combination_items');                // normalized, sorted item IDs in app layer
            $table->string('combination_key', 191);           // e.g. "12-8" (sorted); 191 keeps indexes happy

            // pricing & stock (choose ONE money strategy across DB; shown here as DECIMAL + currency)
            $table->decimal('price_override', 12, 2)->nullable();  // null => fallback to inventory/product price
            $table->char('currency_code', 3)->nullable();          // set when override is used

            // ops/ids
            $table->string('sku_code', 64)->nullable();
            $table->string('barcode', 64)->nullable();
            $table->enum('status', ['active', 'inactive'])->default('active');

            // extra
            $table->json('data')->nullable();

            // indexes & constraints
            $table->unique(['product_inventory_id', 'combination_key'], 'uniq_inventory_combination');
            $table->unique(['product_inventory_id', 'sku_code']);   // scoped uniqueness
            $table->unique('barcode');                               // barcodes are globally unique in practice
            $table->index(['product_inventory_id', 'status'], 'idx_inventory_status');

            $table->auditable();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('product_inventory_variants');
    }
};
