<?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('ticket_email_logs', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('department_id');
            $table->unsignedBigInteger('ticket_id')->nullable();
            $table->unsignedBigInteger('reply_id')->nullable();
            $table->string('from_email');
            $table->string('from_name')->nullable();
            $table->string('subject', 500)->nullable();
            $table->string('message_id', 500)->nullable(); // email Message-ID header
            $table->string('action', 20); // created_ticket, added_reply, skipped, failed
            $table->text('error_message')->nullable();
            $table->string('source_mailbox')->nullable();
            $table->timestamps();

            $table->foreign('department_id')->references('id')->on('ticket_departments')->onDelete('cascade');
            $table->index(['department_id', 'created_at']);
            $table->index('from_email');
        });
    }

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