<?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_sends', function (Blueprint $table)
        {
            $table->id();

            $table->morphs('sendable');

            // Core email fields
            $table->string('to_email');
            $table->string('to_name')->nullable();

            $table->string('from_email')->nullable();
            $table->string('from_name')->nullable();
            $table->string('reply_to')->nullable();

            $table->string('subject');
            $table->longText('html_body')->nullable();
            $table->longText('text_body')->nullable();

            // Templates & variables
            $table->string('template')->nullable();
            $table->json('template_data')->nullable();

            // Scheduling
            $table->timestamp('scheduled_for')->nullable();
            $table->timestamp('sent_at')->nullable();

            // Status & retries
            $table->string('status')->default('pending');
            $table->unsignedTinyInteger('attempts')->default(0);
            $table->timestamp('last_attempt_at')->nullable();

            // Provider details
            $table->string('provider')->nullable();
            $table->string('provider_message_id')->nullable();
            $table->json('provider_response')->nullable();

            // Error handling
            $table->text('error_message')->nullable();

            $table->timestamps();

            $table->index(['status', 'scheduled_for']);
        });
    }

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