<?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
    {
        // First, temporarily change to VARCHAR to allow any values
        DB::statement("ALTER TABLE good_received_notes MODIFY COLUMN status VARCHAR(50) NOT NULL DEFAULT 'pending_qc'");

        // Update existing status values to match new enum
        DB::statement("UPDATE good_received_notes SET status = 'draft' WHERE status = 'pending_qc'");
        DB::statement("UPDATE good_received_notes SET status = 'posted' WHERE status = 'accepted'");

        // Now change to the new enum
        DB::statement("ALTER TABLE good_received_notes MODIFY COLUMN status ENUM('draft', 'posted') NOT NULL DEFAULT 'draft'");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('good_received_notes', function (Blueprint $table) {
            $table->dropIndex(['inward_gate_pass_id']);
            $table->dropIndex(['status']);
            $table->dropConstrainedForeignId('inward_gate_pass_id');

            // Revert status enum
            $table->enum('status', ['pending_qc', 'accepted', 'rejected', 'partial'])->default('pending_qc')->change();
        });
    }
};
