<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * 
     * Creates the discussion_replies table for threaded replies to discussions.
     * Supports nested comments with parent_id for hierarchical structure.
     * 
     * @return void
     */
    public function up(): void
    {
        Schema::create('discussion_replies', function (Blueprint $table) {
            // Primary key
            $table->id();

            // Reply content
            $table->text('content');

            // Foreign keys
            $table->foreignId('discussion_id')
                ->constrained('discussions')
                ->onDelete('cascade');
            $table->foreignId('user_id')
                ->constrained('users')
                ->onDelete('cascade');

            // Parent reply for threaded/nested comments
            $table->foreignId('parent_id')
                ->nullable()
                ->constrained('discussion_replies')
                ->onDelete('cascade');

            // Status
            $table->boolean('is_active')->default(true);
            $table->boolean('is_accepted_answer')->default(false);

            // Engagement metrics
            $table->integer('like_count')->default(0);

            // Depth for nested display optimization
            $table->integer('depth')->default(0);

            // Timestamps
            $table->timestamps();
            $table->softDeletes();

            // Indexes for performance
            $table->index('discussion_id');
            $table->index('user_id');
            $table->index('parent_id');
            $table->index('is_active');
            $table->index('is_accepted_answer');
            $table->index('created_at');
            $table->index(['discussion_id', 'is_active', 'created_at']);
            $table->index(['parent_id', 'is_active']);
        });
    }

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