<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * 
     * 新增批號追溯相關欄位至 inventories 資料表。
     * 批號格式：{商品代號}-{來源國家}-{入庫日期}-{批次流水號}
     * 完整格式（含箱號）：{商品代號}-{來源國家}-{入庫日期}-{批次流水號}-{箱號}
     */
    public function up(): void
    {
        // Step 1: 新增批號相關欄位
        Schema::table('inventories', function (Blueprint $table) {
            // 批號組成：{商品代號}-{來源國家}-{入庫日期}-{批次流水號}
            $table->string('batch_number', 50)->nullable()->after('location')
                ->comment('批號 (格式: AB-VN-20260119-01)');
            $table->string('box_number', 10)->nullable()->after('batch_number')
                ->comment('箱號 (如: 01, 02)');
            
            // 批號解析欄位（方便查詢與排序）
            $table->string('origin_country', 10)->nullable()->after('box_number')
                ->comment('來源國家代碼 (如: VN, TW)');
            $table->date('arrival_date')->nullable()->after('origin_country')
                ->comment('入庫日期');
            $table->date('expiry_date')->nullable()->after('arrival_date')
                ->comment('效期');
            
            // 來源追溯
            $table->foreignId('source_purchase_order_id')->nullable()->after('expiry_date')
                ->constrained('purchase_orders')->nullOnDelete()
                ->comment('來源採購單');
            
            // 品質狀態
            $table->enum('quality_status', ['normal', 'frozen', 'rejected'])
                ->default('normal')->after('source_purchase_order_id')
                ->comment('品質狀態：正常/凍結/退貨');
            $table->text('quality_remark')->nullable()->after('quality_status')
                ->comment('品質異常備註');
        });

        // Step 2: 為現有資料設定預設批號 (LEGACY-{id})
        DB::statement("UPDATE inventories SET batch_number = CONCAT('LEGACY-', id) WHERE batch_number IS NULL");

        // Step 3: 將 batch_number 改為必填
        Schema::table('inventories', function (Blueprint $table) {
            $table->string('batch_number', 50)->nullable(false)->change();
        });

        // Step 4: 新增批號相關索引 (不刪除舊索引，因為有外鍵依賴)
        // 舊的 warehouse_product_unique 保留，新增更精確的批號索引
        Schema::table('inventories', function (Blueprint $table) {
            $table->index(['warehouse_id', 'product_id', 'batch_number'], 'inventories_batch_lookup');
            $table->index(['arrival_date'], 'inventories_arrival_date');
            $table->index(['quality_status'], 'inventories_quality_status');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('inventories', function (Blueprint $table) {
            // 移除索引
            $table->dropIndex('inventories_batch_lookup');
            $table->dropIndex('inventories_arrival_date');
            $table->dropIndex('inventories_quality_status');

            // 移除新增欄位
            $table->dropForeign(['source_purchase_order_id']);
            $table->dropColumn([
                'batch_number',
                'box_number',
                'origin_country',
                'arrival_date',
                'expiry_date',
                'source_purchase_order_id',
                'quality_status',
                'quality_remark',
            ]);
        });
    }
};
