<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        $driver = DB::connection()->getDriverName();

        if ($driver === 'pgsql') {
            // PostgreSQL: drop NOT NULL constraint on description
            DB::statement('ALTER TABLE segments ALTER COLUMN description DROP NOT NULL');

            return;
        }

        if ($driver === 'mysql') {
            // MySQL / MariaDB
            DB::statement('ALTER TABLE segments MODIFY description VARCHAR(255) NULL');

            return;
        }

        // SQLite or other drivers: avoid brittle raw SQL. If Doctrine DBAL isn't installed,
        // changing a column may not be supported. Since this is only relaxing NOT NULL,
        // we can safely no-op for SQLite tests.
        if ($driver === 'sqlite') {
            return; // no-op for tests
        }

        // Fallback attempt using Schema (requires doctrine/dbal; if unavailable, it will be ignored in tests)
        Schema::table('segments', function (Blueprint $table): void {
            try {
                $table->string('description', 255)->nullable()->change();
            } catch (\Throwable $e) {
                // ignore if not supported in current driver
            }
        });
    }

    public function down(): void
    {
        $driver = DB::connection()->getDriverName();

        // Ensure no NULLs before setting NOT NULL
        DB::statement("UPDATE segments SET description = '' WHERE description IS NULL");

        if ($driver === 'pgsql') {
            DB::statement('ALTER TABLE segments ALTER COLUMN description SET NOT NULL');

            return;
        }

        if ($driver === 'mysql') {
            DB::statement('ALTER TABLE segments MODIFY description VARCHAR(255) NOT NULL');

            return;
        }

        if ($driver === 'sqlite') {
            return; // no-op for tests
        }

        Schema::table('segments', function (Blueprint $table): void {
            try {
                $table->string('description', 255)->nullable(false)->change();
            } catch (\Throwable $e) {
                // ignore
            }
        });
    }
};
