<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        if ($this->indexExists('apidetails_api_key_unique')) {
            DB::statement('ALTER TABLE apidetails DROP INDEX apidetails_api_key_unique');
        }

        DB::statement('ALTER TABLE apidetails MODIFY api_key TEXT NULL');
        DB::statement('ALTER TABLE apidetails MODIFY api_secret TEXT NULL');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        DB::statement('ALTER TABLE apidetails MODIFY api_key VARCHAR(255) NULL');
        DB::statement('ALTER TABLE apidetails MODIFY api_secret VARCHAR(255) NULL');

        if (!$this->indexExists('apidetails_api_key_unique')) {
            DB::statement('ALTER TABLE apidetails ADD UNIQUE apidetails_api_key_unique (api_key)');
        }
    }

    private function indexExists(string $indexName): bool
    {
        return !empty(DB::select(
            'SELECT 1 FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ? LIMIT 1',
            ['apidetails', $indexName]
        ));
    }
};
