<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('messenger_conversations', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('channel_id')->constrained('messenger_channels')->cascadeOnDelete();
            $table->string('provider')->index();
            $table->string('external_id')->nullable();
            $table->string('contact_name')->nullable();
            $table->string('contact_handle')->nullable();
            $table->string('status')->default('open')->index();
            $table->timestamp('last_message_at')->nullable()->index();
            $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->json('meta')->nullable();
            $table->timestamps();

            $table->unique(['provider', 'external_id']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('messenger_conversations');
    }
};
