<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * 
     * Adds composite indexes to improve query performance for:
     * - User claim lookups (user_id + event_id)
     * - IP-based claim checks (ip_address + event_id)
     */
    public function up(): void
    {
        Schema::table('event_claims', function (Blueprint $table) {
            // Composite index for user claim lookups (used in index() method)
            if (!$this->hasIndex('event_claims', 'event_claims_user_event_idx')) {
                $table->index(['user_id', 'event_id'], 'event_claims_user_event_idx');
            }
            
            // Composite index for IP-based claim checks
            if (!$this->hasIndex('event_claims', 'event_claims_ip_event_idx')) {
                $table->index(['ip_address', 'event_id'], 'event_claims_ip_event_idx');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('event_claims', function (Blueprint $table) {
            $table->dropIndex('event_claims_user_event_idx');
            $table->dropIndex('event_claims_ip_event_idx');
        });
    }

    /**
     * Check if an index exists
     */
    private function hasIndex(string $table, string $indexName): bool
    {
        $indexes = Schema::getIndexes($table);
        foreach ($indexes as $index) {
            if ($index['name'] === $indexName) {
                return true;
            }
        }
        return false;
    }
};
