<?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('units', function (Blueprint $table) {
            // Add description column
            $table->text('description')->nullable()->after('abbreviation');
            
            // Add status column
            $table->enum('status', ['active', 'inactive'])->default('active')->after('description');
            
            // Add conversion_rate column
            $table->decimal('conversion_rate', 10, 4)->default(1)->after('status');
            
            // Add base_unit_id column (self-referencing foreign key)
            $table->foreignId('base_unit_id')->nullable()->after('conversion_rate')->constrained('units')->onDelete('set null');
            
            // Add is_base_unit column
            $table->boolean('is_base_unit')->default(false)->after('base_unit_id');
            
            // Add indexes
            $table->index('status');
            $table->index('is_base_unit');
            $table->index('base_unit_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('units', function (Blueprint $table) {
            // Remove indexes first
            $table->dropIndex(['status']);
            $table->dropIndex(['is_base_unit']);
            $table->dropIndex(['base_unit_id']);
            
            // Remove foreign key constraint
            $table->dropForeign(['base_unit_id']);
            
            // Remove columns
            $table->dropColumn([
                'description',
                'status',
                'conversion_rate',
                'base_unit_id',
                'is_base_unit'
            ]);
        });
    }
};