<?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('email_logs', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->foreignUuid('investment_id')->nullable()->constrained('investments')->nullOnDelete();
            $table->foreignUuid('investor_id')->nullable()->constrained('investors')->nullOnDelete();
            $table->string('email_type', 50)->comment('payment_confirmation, agreement, welcome, quarterly_report, dividend, kyc_request');
            $table->string('recipient');
            $table->string('subject')->nullable();
            $table->enum('status', ['queued', 'sent', 'delivered', 'opened', 'clicked', 'failed', 'bounced'])->default('queued');
            $table->text('error_message')->nullable();
            $table->string('message_id')->nullable()->comment('Email provider message ID');
            $table->timestamp('sent_at')->nullable();
            $table->timestamp('delivered_at')->nullable();
            $table->timestamp('opened_at')->nullable();
            $table->timestamps();
        });

        Schema::table('email_logs', function (Blueprint $table) {
            $table->index('email_type', 'idx_email_type');
            $table->index('status', 'idx_email_status');
            $table->index('recipient', 'idx_recipient');
        });
    }

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