<?php

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

/**
 * Migration: Create payment_logs table
 * 
 * Stores comprehensive API interaction logs for debugging and auditing purposes.
 * Records all requests and responses from MTN MoMo API calls.
 * 
 * @package PaymentConfigurationModule
 * @author SSHIA Development Team
 */
return new class extends Migration
{
    /**
     * Run the migrations.
     * 
     * Creates the payment_logs table for comprehensive API call logging.
     * Stores request details, response data, and execution metrics.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('payment_logs', function (Blueprint $table) {
            // Primary key
            $table->id();

            // Log Type Classification
            $table->enum('type', ['collection', 'disbursement', 'status_check', 'test'])
                  ->default('collection')
                  ->comment('Type of API operation');

            // API Endpoint Information
            $table->string('endpoint', 500)->comment('API endpoint URL called');

            // Request Details
            $table->json('request_payload')->nullable()->comment('JSON encoded request data (sanitized)');

            // Response Details
            $table->integer('response_status')->nullable()->comment('HTTP response status code');
            $table->json('response_body')->nullable()->comment('JSON encoded response data');

            // Transaction Reference
            $table->string('transaction_reference', 191)->nullable()->comment('External transaction reference ID');

            // Performance Metrics
            $table->integer('execution_time_ms')->nullable()->comment('Request execution time in milliseconds');

            // Error Information
            $table->text('error_message')->nullable()->comment('Error message if request failed');

            // Timestamp (only created_at, logs are immutable)
            $table->timestamp('created_at')->useCurrent();

            // Indexes for performance
            $table->index('type');
            $table->index('transaction_reference');
            $table->index('response_status');
            $table->index('created_at');

            // Composite indexes for common queries
            $table->index(['type', 'created_at']);
            $table->index(['transaction_reference', 'type']);
        });
    }

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