<?php

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

/**
 * wa_conversations — one thread per (channel, wa_id). Powers the two-way Inbox:
 * unread counts, last-message preview, agent assignment / handoff, the Meta 24h
 * customer-service window, and a per-thread AI toggle.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('wa_conversations')) {
            return;
        }

        Schema::create('wa_conversations', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('business_id')->index();
            $table->unsignedInteger('channel_id')->nullable()->index();
            $table->unsignedInteger('contact_id')->nullable();
            $table->string('wa_id', 30)->index();

            $table->enum('status', ['open', 'closed', 'snoozed'])->default('open');
            $table->unsignedInteger('assigned_user_id')->nullable()->index()
                  ->comment('Human agent who has taken the conversation (handoff)');
            $table->boolean('ai_enabled')->default(true)
                  ->comment('Per-thread AI auto-reply override');

            $table->unsignedInteger('unread_count')->default(0);
            $table->enum('last_direction', ['in', 'out'])->nullable();
            $table->string('last_message_excerpt', 200)->nullable();
            $table->timestamp('last_message_at')->nullable();
            $table->timestamp('window_expires_at')->nullable()
                  ->comment('Meta 24h customer-service window');

            $table->json('meta')->nullable();
            $table->timestamps();

            $table->index(['business_id', 'status', 'last_message_at']);
            $table->unique(['business_id', 'channel_id', 'wa_id']);
        });
    }

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