<?php

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

/**
 * Registro append-only de auditoría (accesos, CRUD, excepciones reportadas).
 *
 * @see \App\Models\AuditLog
 * @see \App\Services\AuditLogger
 */
// TODO(regiticket): Particionar por mes o archivar a almacenamiento frío si el volumen crece.
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('audit_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->string('action', 64)->index();
            $table->string('module', 64)->index();
            $table->nullableMorphs('subject');
            $table->string('summary', 512)->nullable();
            $table->json('context')->nullable();
            $table->string('ip_address', 45)->nullable()->index();
            $table->text('user_agent')->nullable();
            $table->string('request_method', 12)->nullable();
            $table->string('request_path', 512)->nullable();
            $table->unsignedSmallInteger('http_status')->nullable();
            $table->timestamp('created_at')->useCurrent();

            $table->index(['module', 'created_at']);
            $table->index(['user_id', 'created_at']);
        });
    }

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