<?php

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

return new class extends Migration {
    public function up(): void
    {
        Schema::create('email_campaign_recipients', function (Blueprint $t) {
            $t->id();
            $t->foreignId('campaign_id')->constrained('email_campaigns')->cascadeOnDelete();
            $t->foreignId('subscriber_id')->nullable()->constrained('email_marketing_subscribers')->nullOnDelete();
            $t->string('email_snapshot');
            $t->string('name_snapshot')->nullable();
            $t->enum('status', ['queued', 'sent', 'failed', 'bounced'])->default('queued');
            $t->char('recipient_token', 32);
            $t->timestamp('sent_at')->nullable();
            $t->timestamp('opened_at')->nullable();
            $t->unsignedInteger('opened_count')->default(0);
            $t->timestamp('clicked_at')->nullable();
            $t->unsignedInteger('click_count')->default(0);
            $t->timestamp('unsubscribed_at')->nullable();
            $t->text('last_error')->nullable();
            $t->unsignedTinyInteger('retry_count')->default(0);
            $t->timestamps();
            $t->unique('recipient_token', 'eml_camp_recip_token_uq');
            $t->index(['campaign_id', 'status'], 'eml_camp_recip_status_idx');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('email_campaign_recipients');
    }
};
