<?php

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

class AddRevisionsTableIndexes extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Fix the 6-second revisions query by adding proper indexes
        if (Schema::hasTable('revisions')) {
            Schema::table('revisions', function (Blueprint $table) {
                // Helper function to check if index exists
                $indexExists = function ($indexName) {
                    $indexes = DB::select("SHOW INDEX FROM revisions WHERE Key_name = ?", [$indexName]);
                    return count($indexes) > 0;
                };

                // Add essential indexes for the slow revisions query
                if (Schema::hasColumn('revisions', 'revisionable_id') && !$indexExists('idx_revisions_revisionable_id')) {
                    $table->index('revisionable_id', 'idx_revisions_revisionable_id');
                }
                
                if (Schema::hasColumn('revisions', 'revisionable_type') && !$indexExists('idx_revisions_revisionable_type')) {
                    $table->index('revisionable_type', 'idx_revisions_revisionable_type');
                }
                
                if (Schema::hasColumn('revisions', 'key') && !$indexExists('idx_revisions_key')) {
                    $table->index('key', 'idx_revisions_key');
                }

                // Composite index for the polymorphic relationship + key filtering (this will be the most effective)
                if (Schema::hasColumn('revisions', 'revisionable_id') && 
                    Schema::hasColumn('revisions', 'revisionable_type') && 
                    Schema::hasColumn('revisions', 'key') && 
                    !$indexExists('idx_revisions_composite')) {
                    $table->index(['revisionable_id', 'revisionable_type', 'key'], 'idx_revisions_composite');
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        if (Schema::hasTable('revisions')) {
            Schema::table('revisions', function (Blueprint $table) {
                $table->dropIndex('idx_revisions_revisionable_id');
                $table->dropIndex('idx_revisions_revisionable_type');
                $table->dropIndex('idx_revisions_key');
                $table->dropIndex('idx_revisions_composite');
            });
        }
    }
}