<?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
    {
        // First, rename columns to match the model naming convention
        // from_unit -> uom_utuh, to_unit -> uom_pakai, description -> notes
        if (Schema::hasColumn('m_item_conversions', 'from_unit')) {
            DB::statement("ALTER TABLE m_item_conversions RENAME COLUMN from_unit TO uom_utuh");
        }
        
        if (Schema::hasColumn('m_item_conversions', 'to_unit')) {
            DB::statement("ALTER TABLE m_item_conversions RENAME COLUMN to_unit TO uom_pakai");
        }
        
        if (Schema::hasColumn('m_item_conversions', 'description')) {
            DB::statement("ALTER TABLE m_item_conversions RENAME COLUMN description TO notes");
        }
        
        // Update uom_utuh and uom_pakai to max 2 characters
        DB::statement("ALTER TABLE m_item_conversions ALTER COLUMN uom_utuh TYPE VARCHAR(2)");
        DB::statement("ALTER TABLE m_item_conversions ALTER COLUMN uom_pakai TYPE VARCHAR(2)");
        
        // Truncate existing data to 2 chars if any longer and uppercase (safety)
        DB::statement("UPDATE m_item_conversions SET uom_utuh = UPPER(SUBSTRING(uom_utuh, 1, 2))");
        DB::statement("UPDATE m_item_conversions SET uom_pakai = UPPER(SUBSTRING(uom_pakai, 1, 2))");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Restore to original length (50)
        DB::statement("ALTER TABLE m_item_conversions ALTER COLUMN uom_utuh TYPE VARCHAR(50)");
        DB::statement("ALTER TABLE m_item_conversions ALTER COLUMN uom_pakai TYPE VARCHAR(50)");
        
        // Rename columns back to original names
        if (Schema::hasColumn('m_item_conversions', 'uom_utuh')) {
            DB::statement("ALTER TABLE m_item_conversions RENAME COLUMN uom_utuh TO from_unit");
        }
        
        if (Schema::hasColumn('m_item_conversions', 'uom_pakai')) {
            DB::statement("ALTER TABLE m_item_conversions RENAME COLUMN uom_pakai TO to_unit");
        }
        
        if (Schema::hasColumn('m_item_conversions', 'notes')) {
            DB::statement("ALTER TABLE m_item_conversions RENAME COLUMN notes TO description");
        }
    }
};
