<?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('m_item_conversions', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('raw_material_id');
            $table->string('from_unit', 50);
            $table->string('to_unit', 50);
            $table->decimal('conversion_factor', 10, 4);
            $table->text('description')->nullable();
            $table->boolean('is_active')->default(true);
            $table->boolean('delete_flag')->default(false);
            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();
            $table->timestamps();

            // Indexes
            $table->index(['raw_material_id', 'delete_flag']);
            $table->index(['is_active', 'delete_flag']);
            
            // Unique constraint untuk mencegah duplikasi konversi
            $table->unique(['raw_material_id', 'from_unit', 'to_unit', 'delete_flag'], 'unique_conversion');

            // Foreign key constraints (jika tabel users dan m_raw_materials sudah ada)
            $table->foreign('raw_material_id')->references('id')->on('m_raw_materials');
            $table->foreign('created_by')->references('id')->on('users');
            $table->foreign('updated_by')->references('id')->on('users');
        });
    }

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