<?php

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

/**
 * Migration: Create Email Configurations Table
 * 
 * Stores encrypted SMTP and IMAP credentials for email configuration.
 * All sensitive fields (usernames, passwords) are encrypted at rest.
 * 
 * MySQL 5.7 Compatibility:
 * - String columns use default 191 character limit for indexed columns
 * - Text columns used for encrypted data (can exceed 191 characters)
 * - InnoDB engine for transaction support
 * 
 * @return void
 */
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('email_configurations', function (Blueprint $table) {
            // Primary key
            $table->id();

            // SMTP Configuration
            $table->string('smtp_host', 191)->comment('SMTP server hostname');
            $table->integer('smtp_port')->default(587)->comment('SMTP server port');
            $table->text('smtp_username')->nullable()->comment('Encrypted SMTP username');
            $table->text('smtp_password')->nullable()->comment('Encrypted SMTP password');
            $table->enum('smtp_encryption', ['tls', 'ssl', 'none'])->default('tls')
                  ->comment('SMTP encryption type');

            // IMAP Configuration
            $table->string('imap_host', 191)->nullable()->comment('IMAP server hostname');
            $table->integer('imap_port')->nullable()->default(993)->comment('IMAP server port');
            $table->text('imap_username')->nullable()->comment('Encrypted IMAP username');
            $table->text('imap_password')->nullable()->comment('Encrypted IMAP password');
            $table->enum('imap_encryption', ['tls', 'ssl', 'none'])->default('ssl')
                  ->comment('IMAP encryption type');

            // Sender Information
            $table->string('from_address', 191)->nullable()->comment('Default sender email address');
            $table->string('from_name', 191)->nullable()->comment('Default sender name');

            // Status
            $table->boolean('is_active')->default(true)->comment('Configuration active status');

            // Timestamps
            $table->timestamps();

            // Indexes for performance
            $table->index('is_active');
            $table->index('created_at');
        });
    }

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