<?php

declare(strict_types=1);

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('audit_logs', function (Blueprint $table) {
            $table->id();

            /*
             * The marketplace audit trail. Section 41 of the spec makes this
             * load-bearing for dispute resolution, so rows are append-only:
             * there is no updated_at and the model blocks updates and deletes.
             */
            $table->enum('actor_type', ['user', 'admin', 'system', 'webhook', 'job'])->default('system');
            $table->foreignId('actor_id')->nullable()->constrained('users')->nullOnDelete();

            // Dotted event name, e.g. listing.price_changed, transfer.completed.
            $table->string('event', 96);

            $table->nullableMorphs('auditable');

            // Attribute snapshots limited to the changed keys.
            $table->json('before')->nullable();
            $table->json('after')->nullable();

            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();

            // Request correlation id, so one user action can be traced across jobs.
            $table->uuid('correlation_id')->nullable();
            $table->json('context')->nullable();

            $table->timestamp('created_at')->nullable();

            $table->index(['event', 'created_at']);
            $table->index(['actor_id', 'created_at']);
            $table->index('correlation_id');
        });
    }

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