<?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
    {
        if (!Schema::hasTable('external_chat_sessions')) {
            Schema::create('external_chat_sessions', function (Blueprint $table) {
                $table->id();
                $table->string('channel', 20)->index();
                $table->string('external_user_id');
                $table->string('external_user_name')->nullable();
                $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
                $table->string('phone', 30)->nullable()->index();
                $table->string('locale', 10)->nullable()->index();
                $table->timestamp('last_message_at')->nullable()->index();
                $table->timestamp('last_outbound_at')->nullable()->index();
                $table->boolean('is_active')->default(true)->index();
                $table->json('meta')->nullable();
                $table->timestamps();

                $table->unique(['channel', 'external_user_id'], 'external_channel_user_unique');
            });
        }

        if (!Schema::hasTable('external_chat_messages')) {
            Schema::create('external_chat_messages', function (Blueprint $table) {
                $table->id();
                $table->foreignId('external_chat_session_id')->constrained('external_chat_sessions')->cascadeOnDelete();
                $table->string('channel', 20)->index();
                $table->string('direction', 20)->index();
                $table->string('role', 20)->index();
                $table->string('provider_message_id')->nullable()->index();
                $table->longText('message')->nullable();
                $table->string('language', 10)->nullable()->index();
                $table->timestamp('sent_at')->nullable()->index();
                $table->json('meta')->nullable();
                $table->timestamps();
            });
        }
    }

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