<?php

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

return new class extends Migration {
    public function up(): void
    {
        if (! Schema::hasColumn('users', 'username')) {
            return;
        }

        DB::table('users')
            ->whereNotNull('username')
            ->update(['username' => DB::raw('LOWER(username)')]);

        $driver = DB::getDriverName();

        try {
            if ($driver === 'mysql') {
                DB::statement(
                    'ALTER TABLE users ADD CONSTRAINT users_username_lowercase_check CHECK (username IS NULL OR BINARY username = LOWER(username))'
                );
            } elseif ($driver === 'pgsql') {
                DB::statement(
                    'ALTER TABLE users ADD CONSTRAINT users_username_lowercase_check CHECK (username IS NULL OR username = LOWER(username))'
                );
            }
        } catch (\Throwable $e) {
            if (! str_contains(strtolower($e->getMessage()), 'already exists')) {
                throw $e;
            }
        }
    }

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

        try {
            if ($driver === 'mysql') {
                DB::statement('ALTER TABLE users DROP CHECK users_username_lowercase_check');
            } elseif ($driver === 'pgsql') {
                DB::statement('ALTER TABLE users DROP CONSTRAINT IF EXISTS users_username_lowercase_check');
            }
        } catch (\Throwable $e) {
            if (! str_contains(strtolower($e->getMessage()), 'check') && ! str_contains(strtolower($e->getMessage()), 'constraint')) {
                throw $e;
            }
        }
    }
};
