<?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->bigIncrements('id');
            $table->unsignedBigInteger('tenant_id')->comment('테넌트ID');
            $table->string('target_type', 100)->comment('리소스 타입 예: model_version, bom_template');
            $table->unsignedBigInteger('target_id')->nullable()->comment('리소스 ID');
            $table->string('action', 50)->comment('액션: created/updated/deleted/released/cloned/items_replaced/diff_viewed');
            $table->json('before')->nullable()->comment('변경 전 스냅샷');
            $table->json('after')->nullable()->comment('변경 후 스냅샷');
            $table->unsignedBigInteger('actor_id')->nullable()->comment('사용자ID(옵션)');
            $table->string('ip', 45)->nullable()->comment('요청 IP');
            $table->string('ua', 255)->nullable()->comment('User-Agent');
            $table->timestamp('created_at')->useCurrent();

            $table->index(['tenant_id', 'target_type', 'target_id', 'created_at'], 'ix_audit_tenant_target_created');
            $table->index(['tenant_id', 'actor_id', 'created_at'], 'ix_audit_tenant_actor_created');
        });
    }

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