<?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('payment_audit_logs', function (Blueprint $table) {
            $table->id();

            // Multi-tenant y actor
            $table->foreignId('company_id')->constrained('companies')->cascadeOnDelete();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();

            // Referencias (nullable porque puede haber logs de intentos / borrados)
            $table->foreignId('payment_id')->nullable()->constrained('payments')->nullOnDelete();
            $table->foreignId('credit_id')->nullable()->constrained('credits')->nullOnDelete();
            $table->foreignId('installment_id')->nullable()->constrained('installments')->nullOnDelete();

            // Acción y contexto
            $table->string('action'); // e.g. created, applied, cascade_applied, reversed, deleted, updated_status
            $table->decimal('amount', 12, 2)->nullable();

            // Estados antes/después (JSON)
            $table->json('previous_data')->nullable();
            $table->json('new_data')->nullable();

            $table->timestamps();

            // índices para búsquedas rápidas
            $table->index(['payment_id']);
            $table->index(['credit_id']);
            $table->index(['installment_id']);
            $table->index(['company_id']);
        });
    }

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