<?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 table exists
        if (!Schema::hasTable('m_raw_materials')) {
            return;
        }

        // Update enum tipe_dokumen to include PO
        // PostgreSQL doesn't support ALTER TYPE directly, so we need to use a workaround
        
        // Step 1: Add new column with new enum
        DB::statement("ALTER TABLE m_raw_materials ADD COLUMN tipe_dokumen_new VARCHAR(2) DEFAULT 'DO'");
        
        // Step 2: Copy data from old column to new column
        DB::statement("UPDATE m_raw_materials SET tipe_dokumen_new = tipe_dokumen");
        
        // Step 3: Drop old column
        DB::statement("ALTER TABLE m_raw_materials DROP COLUMN IF EXISTS tipe_dokumen");
        
        // Step 4: Rename new column to original name
        DB::statement("ALTER TABLE m_raw_materials RENAME COLUMN tipe_dokumen_new TO tipe_dokumen");
        
        // Step 5: Add check constraint for valid values
        DB::statement("ALTER TABLE m_raw_materials ADD CONSTRAINT m_raw_materials_tipe_dokumen_check CHECK (tipe_dokumen IN ('DO', 'PO', 'PR'))");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        if (!Schema::hasTable('m_raw_materials')) {
            return;
        }

        // Revert back to DO and PR only
        // Update any PO values to DO first
        DB::statement("UPDATE m_raw_materials SET tipe_dokumen = 'DO' WHERE tipe_dokumen = 'PO'");
        
        // Drop constraint
        DB::statement("ALTER TABLE m_raw_materials DROP CONSTRAINT IF EXISTS m_raw_materials_tipe_dokumen_check");
        
        // Add old constraint
        DB::statement("ALTER TABLE m_raw_materials ADD CONSTRAINT m_raw_materials_tipe_dokumen_check CHECK (tipe_dokumen IN ('DO', 'PR'))");
    }
};
