<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * Creates the email_messages table for tracking email communications.
     * 
     * Requirements: 3.1, 3.3, 3.7, 3.10, 8.2
     */
    public function up(): void
    {
        Schema::create('email_messages', function (Blueprint $table) {
            // Primary key
            $table->id();

            // Who sent the email
            $table->foreignId('sender_id')
                ->constrained('users')
                ->onDelete('cascade')
                ->comment('User who initiated the email');

            // Recipients stored as JSON arrays
            // Format: [{"email": "user@example.com", "name": "John Doe"}]
            $table->json('to_recipients')->nullable()->comment('Primary recipients');
            $table->json('cc_recipients')->nullable()->comment('CC recipients');
            $table->json('bcc_recipients')->nullable()->comment('BCC recipients');

            // Email content
            $table->string('subject', 191);
            $table->longText('html_body')->nullable()->comment('HTML email content');
            $table->text('text_body')->nullable()->comment('Plain text email content');

            // Template reference (optional)
            $table->foreignId('template_id')
                ->nullable()
                ->constrained('email_templates')
                ->nullOnDelete()
                ->comment('Template used if applicable');

            // Reply tracking
            $table->foreignId('reply_to_id')
                ->nullable()
                ->constrained('email_messages')
                ->nullOnDelete()
                ->comment('Original message this is a reply to');

            $table->string('in_reply_to', 191)->nullable()->comment('Message-ID header for threading');
            $table->text('references')->nullable()->comment('References header for email threading');

            // Scheduling
            $table->timestamp('scheduled_at')->nullable()->comment('When email should be sent');
            $table->timestamp('sent_at')->nullable()->comment('Actual send timestamp');

            // Status tracking
            $table->enum('status', ['draft', 'scheduled', 'sending', 'sent', 'failed', 'partial'])
                ->default('draft')
                ->comment('Current delivery status');

            // Message tracking
            $table->string('message_id', 191)->nullable()->comment('Email Message-ID header');

            // Attachments stored as JSON array
            // Format: [{"name": "document.pdf", "path": "attachments/xxx.pdf", "size": 12345, "mime": "application/pdf"}]
            $table->json('attachments')->nullable()->comment('Array of attachment metadata');

            // Priority for email queue
            $table->enum('priority', ['low', 'normal', 'high'])->default('normal');

            // Recipient selection method
            $table->enum('recipient_type', ['manual', 'csv', 'role_group', 'mixed'])
                ->default('manual')
                ->comment('How recipients were selected');

            // Role group reference (if applicable)
            $table->string('target_role', 100)->nullable()->comment('Target role if role-based selection');

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

            // Standard timestamps
            $table->timestamps();
            $table->softDeletes();

            // Indexes for performance
            $table->index('status');
            $table->index('scheduled_at');
            $table->index('sent_at');
            $table->index(['sender_id', 'status']);
            $table->index('created_at');
            $table->index('reply_to_id');
        });
    }

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