<?php

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

/**
 * Migration: Create Email Logs Table
 * 
 * Stores logs of all email operations (SMTP sends, IMAP receives, tests)
 * for debugging and audit purposes. Includes execution time tracking.
 * 
 * MySQL 5.7 Compatibility:
 * - String columns use default 191 character limit for indexed columns
 * - JSON column for response_body (automatically handled by Laravel)
 * - InnoDB engine for transaction support
 * 
 * @return void
 */
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('email_logs', function (Blueprint $table) {
            // Primary key
            $table->id();

            // Log Type and Details
            $table->enum('type', ['smtp_send', 'imap_receive', 'test'])
                  ->default('smtp_send')
                  ->comment('Type of email operation');

            // Email Details (for SMTP operations)
            $table->string('recipient', 191)->nullable()->comment('Email recipient address');
            $table->string('subject', 191)->nullable()->comment('Email subject line');

            // Status and Response
            $table->enum('status', ['success', 'failed'])->default('success')
                  ->comment('Operation status');
            $table->json('response_body')->nullable()->comment('Full response data as JSON');
            $table->text('error_message')->nullable()->comment('Error message if failed');

            // Performance Tracking
            $table->integer('execution_time_ms')->default(0)
                  ->comment('Operation execution time in milliseconds');

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

            // Indexes for performance
            $table->index('type');
            $table->index('status');
            $table->index('created_at');
            $table->index(['type', 'status']); // Composite index for filtering
            $table->index(['type', 'created_at']); // Composite index for time-based queries
        });
    }

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