<?php

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()->comment('主鍵');

            $table->timestamp('occurred_at')->useCurrent()->comment('事件發生時間');

            $table->string('actor_type')->nullable()->comment('操作者類型');
            $table->unsignedBigInteger('actor_id')->nullable()->comment('操作者ID');
            $table->string('guard', 50)->nullable()->comment('Guard名稱');

            $table->string('action', 100)->nullable()->comment('動作');

            $table->string('route_name')->nullable()->comment('路由名稱');
            $table->text('url')->nullable()->comment('請求 URL');
            $table->string('method', 10)->nullable()->comment('HTTP 方法');
            $table->string('ip', 45)->nullable()->comment('IP 位址');
            $table->text('user_agent')->nullable()->comment('User Agent');
            $table->uuid('request_id')->nullable()->comment('Request ID');

            $table->string('subject_type')->nullable()->comment('主體類型');
            $table->unsignedBigInteger('subject_id')->nullable()->comment('主體 ID');

            $table->unsignedSmallInteger('status_code')->nullable()->comment('HTTP 狀態碼');
            $table->unsignedInteger('duration_ms')->nullable()->comment('耗時（ms）');

            $table->json('payload')->nullable()->comment('內容');

            $table->timestamp('created_at')->nullable()->comment('建立時間');
            $table->timestamp('updated_at')->nullable()->comment('更新時間');

            $table->index(['occurred_at']);
            $table->index(['actor_type', 'actor_id']);
            $table->index(['route_name']);
            $table->index(['subject_type', 'subject_id']);
            $table->index(['request_id']);
        });
    }

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