<?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 before modifying
        if (Schema::hasTable('t_forecasts')) {
            // For PostgreSQL, we need to use raw SQL to modify enum
            DB::statement("ALTER TABLE t_forecasts DROP CONSTRAINT IF EXISTS t_forecasts_status_check");
            DB::statement("ALTER TABLE t_forecasts ADD CONSTRAINT t_forecasts_status_check CHECK (status IN ('Draft', 'Confirmed', 'Cancelled'))");
            
            // Update existing 'Approved' records to 'Confirmed' if any exist
            DB::statement("UPDATE t_forecasts SET status = 'Confirmed' WHERE status = 'Approved'");
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Check if table exists before reverting
        if (Schema::hasTable('t_forecasts')) {
            // Revert back to original enum values
            DB::statement("ALTER TABLE t_forecasts DROP CONSTRAINT IF EXISTS t_forecasts_status_check");
            DB::statement("ALTER TABLE t_forecasts ADD CONSTRAINT t_forecasts_status_check CHECK (status IN ('Draft', 'Approved', 'Cancelled'))");
            
            // Update 'Confirmed' records back to 'Approved'
            DB::statement("UPDATE t_forecasts SET status = 'Approved' WHERE status = 'Confirmed'");
        }
    }
};
