<?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 search_logs table for tracking user searches.
     * Used for analytics and improving search functionality.
     * 
     * @return void
     */
    public function up(): void
    {
        Schema::create('search_logs', function (Blueprint $table) {
            // Primary key
            $table->id();

            // Search query - 191 char limit for MySQL 5.7 compatibility
            $table->string('query', 191);

            // User who searched (nullable for guest searches)
            $table->foreignId('user_id')
                ->nullable()
                ->constrained('users')
                ->onDelete('set null');

            // Search context
            $table->string('search_type', 50)->default('all'); // all, discussions, knowledge_base
            $table->json('filters')->nullable();

            // Results metadata
            $table->integer('results_count')->default(0);
            $table->integer('response_time_ms')->default(0);

            // Session and IP for analytics
            $table->string('session_id', 191)->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->string('user_agent')->nullable();

            // Timestamps
            $table->timestamps();

            // Indexes for performance and analytics
            $table->index('query');
            $table->index('user_id');
            $table->index('search_type');
            $table->index('created_at');
            $table->index(['query', 'search_type']);
            $table->index(['user_id', 'created_at']);
        });
    }

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