<?php

use App\Models\ProjectCharterCompletionRequest;
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 types to the enum
        $types = [
            ProjectCharterCompletionRequest::TYPE_COMPLETE,
            ProjectCharterCompletionRequest::TYPE_CANCEL,
            ProjectCharterCompletionRequest::TYPE_SUSPEND,
        ];

        $this->updateProjectCharterStatusEnum($types);
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Remove completion/closure types from the enum
        $types = ['completion', 'closure'];

        $this->updateProjectCharterStatusEnum($types);
    }

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

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

            case 'pgsql':
                DB::statement('ALTER TABLE project_charter_completion_requests DROP CONSTRAINT IF EXISTS project_charter_completion_requests_type_check');

                DB::statement("ALTER TABLE project_charter_completion_requests 
                    ADD CONSTRAINT project_charter_completion_requests_type_check CHECK (type 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_charter_completion_requests MODIFY COLUMN type ENUM($enumValues) NOT NULL DEFAULT '$defaultValue'");
                break;
        }
    }
};
