<?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->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('template_id')->nullable()->constrained('email_templates')->nullOnDelete();
            $table->foreignId('mail_profile_id')->nullable()->constrained('mail_profiles')->nullOnDelete();
            $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();

            $table->string('message_id')->nullable()->unique();
            $table->string('correlation_id', 100)->nullable();

            $table->string('to_email');
            $table->string('to_name')->nullable();
            $table->json('cc')->nullable();
            $table->json('bcc')->nullable();
            $table->string('from_email')->nullable();
            $table->string('from_name')->nullable();
            $table->string('reply_to')->nullable();

            $table->string('subject', 512);
            $table->string('body_html_hash', 64)->nullable();
            $table->text('body_text_preview')->nullable();
            $table->json('attachments')->nullable();
            $table->string('embed_mode', 16)->default('base64');

            $table->string('status', 20)->index();
            $table->string('error_code', 100)->nullable();
            $table->text('error_message')->nullable();
            $table->string('transport')->nullable();
            $table->json('headers')->nullable();
            $table->unsignedSmallInteger('attempt')->default(1);
            $table->unsignedInteger('duration_ms')->nullable();

            $table->foreignId('client_id')->nullable()->constrained('clients')->nullOnDelete();
            $table->foreignId('client_case_id')->nullable()->constrained('client_cases')->nullOnDelete();
            $table->foreignId('contract_id')->nullable()->constrained('contracts')->nullOnDelete();
            $table->json('extra_context')->nullable();

            $table->timestamp('queued_at')->nullable();
            $table->timestamp('started_at')->nullable();
            $table->timestamp('sent_at')->nullable();
            $table->timestamp('failed_at')->nullable();
            $table->string('ip', 45)->nullable();

            $table->timestamps();

            $table->index(['template_id', 'created_at']);
            $table->index(['to_email', 'created_at']);
            $table->index(['status', 'created_at']);
            $table->index(['client_id', 'client_case_id', 'contract_id']);
        });
    }

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