<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('product_units', function (Blueprint $table) {
            $table->id();
            $table->ulid('uuid')->unique();
            $table->foreignId('product_id')->constrained('products')->cascadeOnDelete();
            // No FK yet — product_variants is created in Phase A1 (constraint added there).
            $table->unsignedBigInteger('product_variant_id')->nullable();
            $table->foreignId('unit_id')->constrained('unit_of_measures')->restrictOnDelete();
            $table->decimal('conversion_factor', 12, 4);
            $table->decimal('sale_price', 12, 2)->nullable();
            $table->string('barcode', 50)->nullable()->unique();
            $table->boolean('is_default_sale_unit')->default(false);
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('deleted_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->softDeletes();

            $table->unique(['product_id', 'product_variant_id', 'unit_id'], 'product_units_product_variant_unit_unique');
            $table->index('product_variant_id');
        });
    }

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