<?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('contact_messages', function (Blueprint $t) {
            $t->id();
            $t->foreignId('solicitor_id')->constrained()->cascadeOnDelete();

            $t->string('channel', 16);
            $t->string('direction', 16)->default('outbound');
            $t->string('provider', 24)->nullable();
            $t->string('status', 24)->default('queued');
            $t->string('origin_type', 32)->default('manual');
            $t->json('origin_detail')->nullable();

            $t->nullableMorphs('messageable');
            $t->nullableMorphs('related');

            $t->foreignId('template_id')->nullable()
                ->constrained('contact_templates')->nullOnDelete();
            $t->foreignId('sender_email_id')->nullable()
                ->constrained('solicitor_email_senders')->nullOnDelete();
            $t->foreignId('sender_phone_id')->nullable()
                ->constrained('solicitor_phone_numbers')->nullOnDelete();

            $t->string('recipient_name')->nullable();
            $t->string('recipient_email')->nullable();
            $t->string('recipient_phone', 32)->nullable();

            $t->string('sender_display')->nullable();
            $t->string('sender_value')->nullable();
            $t->string('reply_to')->nullable();

            $t->string('subject', 512)->nullable();
            $t->longText('body_text')->nullable();
            $t->longText('body_html')->nullable();
            $t->json('rendered_placeholders')->nullable();

            $t->string('provider_message_id', 191)->nullable()->index();
            $t->json('provider_payload')->nullable();
            $t->text('failure_reason')->nullable();

            $t->string('thread_key', 191)->nullable()->index();
            $t->string('in_reply_to_provider_id', 191)->nullable();

            $t->string('dedupe_hash', 64)->nullable();

            $t->timestamp('queued_at')->nullable();
            $t->timestamp('sent_at')->nullable();
            $t->timestamp('delivered_at')->nullable();
            $t->timestamp('opened_at')->nullable();
            $t->timestamp('failed_at')->nullable();

            $t->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $t->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();

            $t->timestamps();
            $t->softDeletes();

            $t->index(['solicitor_id', 'channel', 'status']);
            $t->index(['solicitor_id', 'direction', 'created_at']);
            $t->index(['solicitor_id', 'template_id', 'created_at']);
        });
    }

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