<?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::table('t_forecast_details', function (Blueprint $table) {
            // Add store_id column after forecast_header_id
            if (!Schema::hasColumn('t_forecast_details', 'store_id')) {
                $table->unsignedBigInteger('store_id')->nullable()->after('forecast_header_id');
                
                // Add foreign key constraint
                $table->foreign('store_id')
                    ->references('id')
                    ->on('m_stores')
                    ->onDelete('restrict');
                
                // Add index for better query performance
                $table->index(['store_id', 'raw_material_id', 'forecast_date'], 'idx_store_material_date');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('t_forecast_details', function (Blueprint $table) {
            if (Schema::hasColumn('t_forecast_details', 'store_id')) {
                // Drop foreign key and index first
                $table->dropForeign(['store_id']);
                $table->dropIndex('idx_store_material_date');
                $table->dropColumn('store_id');
            }
        });
    }
};
