<?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
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->index('status', 'users_status_index');
            $table->index('department_id', 'users_department_id_index');
            $table->index(['status', 'department_id'], 'users_status_department_index');
            $table->index('name', 'users_name_index');
        });

        Schema::table('audit_logs', function (Blueprint $table) {
            $table->index('user_id', 'audit_logs_user_id_index');
            $table->index('action', 'audit_logs_action_index');
            $table->index(['user_id', 'created_at'], 'audit_logs_user_created_index');
        });

        Schema::table('settings', function (Blueprint $table) {
            $table->index('category', 'settings_category_index');
        });

        Schema::table('installed_modules', function (Blueprint $table) {
            $table->index('status', 'installed_modules_status_index');
            $table->index('module_uuid', 'installed_modules_module_uuid_index');
        });

        if (Schema::getConnection()->getDriverName() === 'mysql') {
            DB::statement('ALTER TABLE users ADD FULLTEXT INDEX users_search_fulltext (name, email)');
        }
    }

    public function down(): void
    {
        if (Schema::getConnection()->getDriverName() === 'mysql') {
            DB::statement('ALTER TABLE users DROP INDEX users_search_fulltext');
        }

        Schema::table('installed_modules', function (Blueprint $table) {
            $table->dropIndex('installed_modules_status_index');
            $table->dropIndex('installed_modules_module_uuid_index');
        });

        Schema::table('settings', function (Blueprint $table) {
            $table->dropIndex('settings_category_index');
        });

        Schema::table('audit_logs', function (Blueprint $table) {
            $table->dropIndex('audit_logs_user_id_index');
            $table->dropIndex('audit_logs_action_index');
            $table->dropIndex('audit_logs_user_created_index');
        });

        Schema::table('users', function (Blueprint $table) {
            $table->dropIndex('users_status_index');
            $table->dropIndex('users_department_id_index');
            $table->dropIndex('users_status_department_index');
            $table->dropIndex('users_name_index');
        });
    }
};
