<?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 knowledge_base_answers table for answers to knowledge base questions.
     * Supports accepted answers and helpful voting.
     * 
     * @return void
     */
    public function up(): void
    {
        Schema::create('knowledge_base_answers', function (Blueprint $table) {
            // Primary key
            $table->id();

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

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

            // Status and acceptance
            $table->boolean('is_published')->default(true);
            $table->boolean('is_accepted')->default(false);
            $table->timestamp('accepted_at')->nullable();
            $table->foreignId('accepted_by')
                ->nullable()
                ->constrained('users')
                ->onDelete('set null');

            // Engagement metrics
            $table->integer('helpful_count')->default(0);
            $table->integer('not_helpful_count')->default(0);
            $table->integer('view_count')->default(0);

            // Sorting order (for multiple answers)
            $table->integer('sort_order')->default(0);

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

            // Indexes for performance
            $table->index('question_id');
            $table->index('user_id');
            $table->index('is_published');
            $table->index('is_accepted');
            $table->index('created_at');
            $table->index(['question_id', 'is_published', 'is_accepted'], 'kba_q_pub_accepted_idx');
            $table->index(['question_id', 'is_published', 'sort_order'], 'kba_q_pub_sort_idx');

            // Full-text index for search
            $table->fullText('content');
        });
    }

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