<?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->string('notification_type'); // Notification class name
            $table->string('recipient_type')->nullable(); // Model class (User, Client, etc)
            $table->unsignedBigInteger('recipient_id')->nullable();
            $table->string('recipient_email');
            $table->string('subject');
            $table->string('channel')->default('mail'); // mail, database, etc
            $table->enum('status', ['pending', 'sent', 'failed', 'retrying'])->default('pending');
            $table->unsignedTinyInteger('attempts')->default(0);
            $table->timestamp('last_attempt_at')->nullable();
            $table->timestamp('sent_at')->nullable();
            $table->timestamp('failed_at')->nullable();
            $table->text('error_message')->nullable();
            $table->json('metadata')->nullable(); // Additional data
            $table->timestamps();

            // Indexes for common queries
            $table->index(['status', 'created_at']);
            $table->index(['notification_type', 'status']);
            $table->index(['recipient_email', 'created_at']);
            $table->index('recipient_id');
        });
    }

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