<?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('t_forecast_details', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('forecast_header_id');
            $table->unsignedBigInteger('raw_material_id');
            $table->date('forecast_date');
            $table->decimal('forecast_qty', 15, 4)->default(0);
            $table->text('notes')->nullable();
            $table->boolean('delete_flag')->default(0);
            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();
            $table->timestamps();

            // Foreign keys
            $table->foreign('forecast_header_id')->references('id')->on('t_forecasts')->onDelete('cascade');
            $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');

            // Indexes
            $table->index(['forecast_header_id']);
            $table->index(['raw_material_id']);
            $table->index(['forecast_date']);
            $table->index(['delete_flag']);

            // Unique constraint to prevent duplicate entries
            $table->unique(['forecast_header_id', 'raw_material_id', 'forecast_date'], 'unique_forecast_detail');
        });
    }

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