<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('whatsapp_messages', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('academy_id')->index();
            $table->string('wa_message_id')->nullable()->index();
            $table->string('phone_number', 20);
            $table->string('type', 30);
            $table->text('content');
            $table->string('status', 30)->default('pending');
            $table->text('error_message')->nullable();
            $table->jsonb('payload')->default('{}');
            $table->jsonb('response')->default('{}');
            $table->unsignedBigInteger('sent_by')->nullable()->index();
            $table->timestamp('sent_at')->nullable();
            $table->timestamp('delivered_at')->nullable();
            $table->timestamp('read_at')->nullable();
            $table->timestamps();

            $table->index(['academy_id', 'created_at']);
            $table->index(['phone_number', 'created_at']);
        });

        DB::statement("ALTER TABLE whatsapp_messages ADD CONSTRAINT whatsapp_messages_type_check CHECK (type IN ('template', 'text', 'image', 'document'))");
        DB::statement("ALTER TABLE whatsapp_messages ADD CONSTRAINT whatsapp_messages_status_check CHECK (status IN ('pending', 'sent', 'delivered', 'read', 'failed'))");
    }

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