<?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('messages', function (Blueprint $table) {
            $table->id();
            $table->foreignId('conversation_id')->constrained()->onDelete('cascade');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->enum('type', ['text', 'image', 'video', 'audio', 'file', 'system'])->default('text');
            $table->text('content')->nullable();
            $table->json('metadata')->nullable(); // For storing system message data, edited history, etc.
            $table->string('client_generated_id', 64)->nullable(); // For idempotent sends
            $table->unsignedBigInteger('reply_to_message_id')->nullable();
            $table->timestamp('edited_at')->nullable();
            $table->boolean('is_deleted')->default(false);
            $table->timestamp('deleted_at')->nullable();
            $table->timestamps();

            $table->foreign('reply_to_message_id')->references('id')->on('messages')->onDelete('set null');
            
            $table->unique(['user_id', 'client_generated_id']);
            $table->index(['conversation_id', 'created_at']);
            $table->index(['conversation_id', 'id']);
            $table->index(['user_id', 'created_at']);
            $table->index(['type', 'created_at']);
        });
    }

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