<?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::create('audit_logs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('user_id')->nullable()->constrained('users');
            $table->string('auditable_type');
            $table->unsignedBigInteger('auditable_id');
            $table->string('action', 20);
            $table->jsonb('old_values')->nullable();
            $table->jsonb('new_values')->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->string('user_agent')->nullable();
            $table->string('url')->nullable();
            $table->boolean('is_financial')->default(false);
            $table->timestamp('created_at')->useCurrent();

            // Composite indexes for common queries
            $table->index(['academy_id', 'auditable_type', 'auditable_id'], 'audit_logs_auditable_index');
            $table->index(['user_id', 'created_at'], 'audit_logs_user_time_index');
            $table->index(['auditable_type', 'action', 'created_at'], 'audit_logs_type_action_time_index');
            $table->index(['is_financial', 'created_at'], 'audit_logs_financial_time_index');
            $table->index('created_at', 'audit_logs_retention_index');
        });

        DB::statement("ALTER TABLE audit_logs ADD CONSTRAINT audit_logs_action_check CHECK (action IN ('created', 'updated', 'deleted', 'restored'))");
    }

    public function down(): void
    {
        Schema::dropIfExists('audit_logs');
    }
};
