<?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 indexes to optimize single session middleware queries:
     * - Composite index for tokenable_type, tokenable_id, name (most common query pattern)
     * - Index on name column (for filtering impersonation tokens)
     * - Composite index for tokenable_type, tokenable_id, created_at (for fresh token checks)
     */
    public function up(): void
    {
        Schema::table('personal_access_tokens', function (Blueprint $table) {
            // Composite index for finding user tokens by type, id, and name
            // This optimizes queries like: where tokenable_type = X AND tokenable_id = Y AND name = Z
            $table->index(['tokenable_type', 'tokenable_id', 'name'], 'pat_tokenable_type_id_name_index');
            
            // Index on name for filtering impersonation tokens and token types
            $table->index('name', 'pat_name_index');
            
            // Composite index for checking older tokens by user and creation date
            // This optimizes queries checking for older tokens during fresh login detection
            $table->index(['tokenable_type', 'tokenable_id', 'created_at'], 'pat_tokenable_created_index');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('personal_access_tokens', function (Blueprint $table) {
            $table->dropIndex('pat_tokenable_type_id_name_index');
            $table->dropIndex('pat_name_index');
            $table->dropIndex('pat_tokenable_created_index');
        });
    }
};
