<?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('products', function (Blueprint $table) {
            // Drop old string columns
            $table->dropColumn(['base_unit', 'large_unit', 'purchase_unit']);

            // Add new foreign key columns
            $table->foreignId('base_unit_id')->nullable()->after('specification')->constrained('units')->nullOnDelete()->comment('基本庫存單位ID');
            $table->foreignId('large_unit_id')->nullable()->after('base_unit_id')->constrained('units')->nullOnDelete()->comment('大單位ID');
            $table->foreignId('purchase_unit_id')->nullable()->after('conversion_rate')->constrained('units')->nullOnDelete()->comment('採購單位ID');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('products', function (Blueprint $table) {
            // Remove foreign keys
            $table->dropForeign(['base_unit_id']);
            $table->dropForeign(['large_unit_id']);
            $table->dropForeign(['purchase_unit_id']);
            $table->dropColumn(['base_unit_id', 'large_unit_id', 'purchase_unit_id']);

            // Add back string columns (nullable since data is lost)
            $table->string('base_unit')->nullable()->comment('基本庫存單位 (e.g. g, ml)');
            $table->string('large_unit')->nullable()->comment('大單位 (e.g. 桶, 箱)');
            $table->string('purchase_unit')->nullable()->comment('採購單位');
        });
    }
};
