<?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.
     */
    public function up(): void
    {
        // Check if uom_id column already exists
        if (!Schema::hasColumn('items', 'uom_id')) {
            Schema::table('items', function (Blueprint $table) {
                // Add uom_id foreign key
                $table->foreignId('uom_id')->nullable()->after('item_category_id')->constrained('uoms')->nullOnDelete();
            });
        }

        // Add index for better performance
        if (!Schema::hasIndex('items', ['uom_id', 'type'])) {
            Schema::table('items', function (Blueprint $table) {
                $table->index(['uom_id', 'type']);
            });
        }

        // First change the enum to include both old and new values
        Schema::table('items', function (Blueprint $table) {
            $table->enum('type', ['raw_material', 'finished_product', 'RM', 'FG'])->change();
        });

        // Update existing data to use new enum values
        DB::statement("UPDATE items SET type = 'RM' WHERE type = 'raw_material'");
        DB::statement("UPDATE items SET type = 'FG' WHERE type = 'finished_product'");

        // Now change the enum to only include new values
        Schema::table('items', function (Blueprint $table) {
            $table->enum('type', ['RM', 'FG'])->change();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('items', function (Blueprint $table) {
            $table->dropIndex(['uom_id', 'type']);
            $table->dropConstrainedForeignId('uom_id');
            $table->enum('type', ['raw_material', 'finished_product'])->change();
        });
    }
};
