<?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
{
    private const PARENT_INDEX = 'users_parent_id_idx_2';
    private const POSITION_INDEX = 'users_position_idx';

    public function up(): void
    {
        if (! Schema::hasTable('users')) {
            return;
        }

        if (Schema::hasColumn('users', 'parent_id') && ! $this->indexExists('users', self::PARENT_INDEX)) {
            Schema::table('users', function (Blueprint $table): void {
                $table->index('parent_id', self::PARENT_INDEX);
            });
        }

        if (Schema::hasColumn('users', 'position') && ! $this->indexExists('users', self::POSITION_INDEX)) {
            Schema::table('users', function (Blueprint $table): void {
                $table->index('position', self::POSITION_INDEX);
            });
        }
    }

    public function down(): void
    {
        if (! Schema::hasTable('users')) {
            return;
        }

        if ($this->indexExists('users', self::PARENT_INDEX)) {
            Schema::table('users', function (Blueprint $table): void {
                $table->dropIndex(self::PARENT_INDEX);
            });
        }

        if ($this->indexExists('users', self::POSITION_INDEX)) {
            Schema::table('users', function (Blueprint $table): void {
                $table->dropIndex(self::POSITION_INDEX);
            });
        }
    }

    private function indexExists(string $table, string $name): bool
    {
        $driver = DB::getDriverName();

        return match ($driver) {
            'mysql' => count(DB::select("SHOW INDEX FROM `{$table}` WHERE Key_name = ?", [$name])) > 0,
            'pgsql' => count(DB::select('SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?', [$table, $name])) > 0,
            'sqlite' => collect(DB::select("PRAGMA index_list('{$table}')"))->contains(fn ($row) => ($row->name ?? null) === $name),
            default => false,
        };
    }
};

