<?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.safety_stock 資料遷移至 warehouse_product_safety_stocks 表格
     */
    public function up(): void
    {
        // 1. 遷移現有資料：從 inventories 提取唯一的 warehouse_id + product_id 組合及其 safety_stock
        DB::statement("
            INSERT INTO warehouse_product_safety_stocks (warehouse_id, product_id, safety_stock, created_at, updated_at)
            SELECT 
                warehouse_id, 
                product_id, 
                MAX(safety_stock) as safety_stock,
                NOW(),
                NOW()
            FROM inventories
            WHERE safety_stock IS NOT NULL AND safety_stock > 0
            GROUP BY warehouse_id, product_id
            ON DUPLICATE KEY UPDATE safety_stock = VALUES(safety_stock), updated_at = NOW()
        ");

        // 2. 移除 inventories 表的 safety_stock 欄位
        Schema::table('inventories', function (Blueprint $table) {
            $table->dropColumn('safety_stock');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // 1. 在 inventories 表重新加入 safety_stock 欄位
        Schema::table('inventories', function (Blueprint $table) {
            $table->decimal('safety_stock', 10, 2)->nullable()->after('quantity');
        });

        // 2. 將資料還原回 inventories (更新同商品所有批號)
        DB::statement("
            UPDATE inventories i
            INNER JOIN warehouse_product_safety_stocks ss 
                ON i.warehouse_id = ss.warehouse_id AND i.product_id = ss.product_id
            SET i.safety_stock = ss.safety_stock
        ");
    }
};
