<?php

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

/**
 * Phase 1: Create financial audit logs table.
 *
 * Comprehensive audit trail for all income and expense operations.
 * Unlike existing audit logs, this captures full before/after snapshots
 * and includes security context (IP, user agent).
 *
 * PURPOSE:
 * - Regulatory compliance
 * - Fraud detection
 * - Dispute resolution
 * - Financial reconciliation
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('financial_audit_logs', function (Blueprint $table) {
            $table->id();

            // Multi-tenant isolation
            $table->foreignId('company_id')
                ->constrained()
                ->cascadeOnDelete();

            // Who performed the action
            $table->foreignId('user_id')
                ->constrained()
                ->cascadeOnDelete();

            // Polymorphic relationship to Income or Expense
            $table->string('auditable_type', 100)
                ->comment('Model class: App\\Models\\Income or App\\Models\\Expense');

            $table->unsignedBigInteger('auditable_id')
                ->comment('ID of the income or expense record');

            // What happened
            $table->string('action', 50)
                ->comment('created, updated, deleted, locked, unlocked, approved, rejected');

            // Data snapshots
            $table->json('previous_data')
                ->nullable()
                ->comment('State before the change (null for creates)');

            $table->json('new_data')
                ->nullable()
                ->comment('State after the change (null for deletes)');

            $table->json('changed_fields')
                ->nullable()
                ->comment('List of fields that were modified');

            // Financial impact summary (for quick queries)
            $table->decimal('amount_before', 15, 2)
                ->nullable()
                ->comment('Amount before change');

            $table->decimal('amount_after', 15, 2)
                ->nullable()
                ->comment('Amount after change');

            $table->decimal('amount_delta', 15, 2)
                ->nullable()
                ->comment('Difference (positive = increase, negative = decrease)');

            // Security context
            $table->string('ip_address', 45)
                ->nullable()
                ->comment('IPv4 or IPv6 address');

            $table->text('user_agent')
                ->nullable()
                ->comment('Browser/client user agent');

            $table->string('session_id', 255)
                ->nullable()
                ->comment('Session identifier for correlation');

            // Context
            $table->string('reason', 500)
                ->nullable()
                ->comment('User-provided reason for the change');

            $table->string('triggered_by', 100)
                ->nullable()
                ->comment('What triggered this: manual, system, payment_sync, etc.');

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

            // Indexes for common queries
            $table->index(['auditable_type', 'auditable_id'], 'idx_fal_auditable');
            $table->index(['company_id', 'created_at'], 'idx_fal_company_date');
            $table->index(['company_id', 'action'], 'idx_fal_company_action');
            $table->index(['user_id', 'created_at'], 'idx_fal_user_date');
            $table->index(['company_id', 'auditable_type', 'created_at'], 'idx_fal_company_type_date');
        });
    }

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