<?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('wa_messages', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
            $table->foreignId('patient_id')->nullable()->constrained()->nullOnDelete();
            $table->string('to_phone', 32);          // E.164 normalized
            $table->string('template_key', 40)->nullable();
            $table->text('body');                     // rendered text actually sent
            $table->string('status', 20)->default('queued');
            $table->string('direction', 10)->default('outbound');

            // Provider tracking
            $table->string('provider', 20)->nullable();      // meta|twilio|log
            $table->string('provider_message_id', 128)->nullable()->index();
            $table->string('failure_code', 40)->nullable();
            $table->text('failure_reason')->nullable();

            // Retry queue
            $table->unsignedTinyInteger('attempts')->default(0);
            $table->timestamp('next_attempt_at')->nullable()->index();

            // PDF attachment (v2.1-C): plan / invoice
            $table->string('media_path')->nullable();
            $table->string('media_mime', 100)->nullable();
            $table->string('media_filename', 190)->nullable();

            // Polymorphic source (appointment / installment / recall / invoice…)
            $table->nullableMorphs('related');

            $table->timestamp('sent_at')->nullable();
            $table->timestamp('delivered_at')->nullable();
            $table->timestamp('read_at')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            $table->index(['tenant_id', 'patient_id', 'created_at']);
            $table->index(['tenant_id', 'status']);
            $table->index(['status', 'next_attempt_at']); // retry sweeper
        });
    }

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