<?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 discussions table for user-generated discussion posts.
     * Each discussion belongs to a topic and has a user author.
     * 
     * @return void
     */
    public function up(): void
    {
        Schema::create('discussions', function (Blueprint $table) {
            // Primary key
            $table->id();

            // Discussion content - 191 char limit for MySQL 5.7 compatibility
            $table->string('title', 191);
            $table->string('slug', 191)->unique();
            $table->text('content');
            $table->text('excerpt')->nullable();

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

            // Status management
            $table->enum('status', ['draft', 'published', 'archived', 'pending_review'])
                ->default('published');
            $table->boolean('is_active')->default(true);
            $table->boolean('is_pinned')->default(false);
            $table->boolean('is_featured')->default(false);

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

            // SEO metadata
            $table->string('meta_title', 191)->nullable();
            $table->text('meta_description')->nullable();
            $table->string('meta_keywords', 191)->nullable();

            // Last activity tracking
            $table->timestamp('last_activity_at')->nullable();
            $table->foreignId('last_reply_user_id')
                ->nullable()
                ->constrained('users')
                ->onDelete('set null');

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

            // Indexes for performance
            $table->index('topic_id');
            $table->index('user_id');
            $table->index('status');
            $table->index('is_active');
            $table->index('is_pinned');
            $table->index('is_featured');
            $table->index('created_at');
            $table->index('last_activity_at');
            $table->index(['topic_id', 'status', 'is_active']);
            $table->index(['status', 'is_active', 'created_at']);
        });
    }

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