<?php

use App\Models\ProjectCharter;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Add new completion/closure statuses to the enum
        $statuses = [
            ProjectCharter::STATUS_DRAFT,
            ProjectCharter::STATUS_AWAITING_APPROVAL,
            ProjectCharter::STATUS_APPROVED,
            ProjectCharter::STATUS_REJECTED,
            ProjectCharter::STATUS_COMPLETED,
            ProjectCharter::STATUS_CANCELED,
            ProjectCharter::STATUS_SUSPENDED,
        ];

        $this->updateProjectCharterStatusEnum($statuses);
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Remove completion/closure statuses from the enum
        $statuses = [
            ProjectCharter::STATUS_DRAFT,
            ProjectCharter::STATUS_AWAITING_APPROVAL,
            ProjectCharter::STATUS_APPROVED,
            ProjectCharter::STATUS_REJECTED,
        ];

        $this->updateProjectCharterStatusEnum($statuses);
    }

    /**
     * Update the project charter status enum for different database drivers
     */
    private function updateProjectCharterStatusEnum(array $statuses): void
    {
        $driver = DB::connection()->getDriverName();
        $enumValues = "'".implode("','", $statuses)."'";
        $defaultValue = ProjectCharter::STATUS_DRAFT;

        switch ($driver) {
            case 'mysql':
                DB::statement("ALTER TABLE project_charters MODIFY COLUMN status ENUM($enumValues) NOT NULL DEFAULT '$defaultValue'");
                break;

            case 'pgsql':
                DB::statement('ALTER TABLE project_charters DROP CONSTRAINT IF EXISTS project_charters_status_check');

                DB::statement("ALTER TABLE project_charters 
                    ADD CONSTRAINT project_charters_status_check CHECK (status IN ($enumValues))");
                break;

            case 'sqlite':
                // SQLite doesn't have native ENUM support
                // We'll skip ENUM constraints for SQLite and rely on application-level validation
                Log::info('SQLite detected. ENUM constraints not applied - relying on application validation.');
                break;

            default:
                // Fallback for other databases - attempt MySQL syntax but warn
                Log::warning("Unsupported database driver: $driver. Attempting MySQL syntax.");
                DB::statement("ALTER TABLE project_charters MODIFY COLUMN status ENUM($enumValues) NOT NULL DEFAULT '$defaultValue'");
                break;
        }
    }
};
