<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posting_logs', function (Blueprint $table) {
            $table->id();
            $table->string('source_module', 100);
            $table->string('source_entity_type', 100);
            $table->unsignedBigInteger('source_entity_id');
            $table->string('target_module', 100);
            $table->string('target_entity_type', 100);
            $table->unsignedBigInteger('target_entity_id')->nullable();
            $table->string('action', 50);
            $table->string('status', 50);
            $table->string('description', 500)->nullable();
            $table->decimal('amount', 15, 2)->nullable();
            $table->json('old_values')->nullable();
            $table->json('new_values')->nullable();
            $table->text('error_message')->nullable();
            $table->unsignedInteger('retry_count')->default(0);
            $table->unsignedBigInteger('posted_by')->nullable();
            $table->timestamp('posted_at');
            $table->timestamps();

            // Foreign key for posted_by
            $table->foreign('posted_by')
                ->references('id')
                ->on('users')
                ->nullOnDelete();

            // Indexes for performance
            $table->index('source_module');
            $table->index('target_module');
            $table->index('status');
            $table->index('posted_at');
            $table->index(['source_module', 'source_entity_type', 'source_entity_id'], 'posting_logs_source_idx');
            $table->index(['target_module', 'target_entity_type', 'target_entity_id'], 'posting_logs_target_idx');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posting_logs');
    }
};
