<?php

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

/**
 * Audit Log — her destructive action'ı kayda alır
 *
 * Phase 1 Epic 14 — 2FA + Audit Log + Security Hardening
 * KVKK uyumluluğu: PII maskelenmiş, retention 90 gün (cron ile temizlenir)
 * Append-only — updated_at YOK, hiç edit edilmez
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('audit_log', function (Blueprint $table) {
            $table->id();

            // Aktör
            $table->foreignId('user_id')
                ->nullable()
                ->constrained('users')
                ->nullOnDelete()
                ->comment('null = sistem aksiyonu (cron, queue worker)');

            // Bağlam
            $table->string('ip_address', 45)->nullable()
                ->comment('IPv4 veya IPv6 — KVKK için truncated kaydedilir');
            $table->text('user_agent')->nullable();
            $table->string('session_id', 64)->nullable();

            // Aksiyon
            $table->string('action', 64)
                ->comment('account.created, domain.deleted, db.user.password_changed, vs.');
            $table->string('target_type', 64)->nullable()
                ->comment('Polymorphic — Account, Domain, DnsRecord, vs.');
            $table->unsignedBigInteger('target_id')->nullable();

            // Veri (KVKK: PII maskelenmiş olmalı — örn email kısmen, parola asla)
            $table->json('before')->nullable();
            $table->json('after')->nullable();
            $table->json('metadata')->nullable()
                ->comment('Ek kontekst — provisioning_job_id, sysapi_exit_code, vs.');

            // Sonuç
            $table->enum('outcome', ['success', 'failure', 'partial'])->default('success');
            $table->text('error_message')->nullable();

            // Append-only — sadece created_at
            $table->timestamp('created_at')->useCurrent();

            $table->index('user_id');
            $table->index('action');
            $table->index(['target_type', 'target_id']);
            $table->index('created_at');
            $table->index(['outcome', 'created_at']);
        });
    }

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