<?php

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

/**
 * Knowledge Base query logs — one row per AI reply that consumed KB context.
 *
 * Existing `ai_usage_logs` only tracks tokens/cost. It does not record the
 * actual question, the answer, which chunks were cited, or whether the
 * reply was helpful. Without that history we cannot build the Insights
 * dashboard (deflection rate, top questions, knowledge gaps, thumbs
 * feedback) that turns the silent backend RAG into a visibly sellable
 * "AI Knowledge Agent" feature.
 *
 * This table is append-only at runtime. Reads happen from the admin
 * Insights page only — workspace-scoped via `workspace_id`.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('kb_query_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('workspace_id')->constrained()->cascadeOnDelete();

            // The conversation this Q&A happened inside, if any.
            // Nullable because playground / test panel questions also log here
            // but have no conversation.
            $table->foreignId('conversation_id')->nullable()
                ->constrained('conversations')->nullOnDelete();
            $table->string('channel', 32)->nullable(); // whatsapp, email, widget, instagram, facebook, playground

            // What the customer asked + how the agent answered.
            $table->text('question');
            $table->text('answer');

            // Which chunks fed the answer. Stored as a JSON array of kb_chunks.id
            // — references kb_chunks(id) loosely (no FK because chunks can be
            // deleted but we want the log to survive the citation pointers).
            $table->json('cited_chunk_ids')->nullable();

            // Heuristic 0-100 confidence from AIManager::estimateConfidence().
            // Persisted so the Insights dashboard can chart confidence over
            // time and we can audit low-confidence answers.
            $table->unsignedTinyInteger('confidence')->default(50);

            // True when confidence was below the workspace threshold and we
            // returned the "I don't know — connect to human?" fallback instead
            // of the raw LLM output. Powers the "knowledge gaps" report.
            $table->boolean('was_fallback')->default(false);

            // Customer thumbs feedback. Nullable = not rated yet.
            // Set via POST /knowledge-base/feedback/{queryId}.
            $table->boolean('was_helpful')->nullable();

            // Provider/model snapshot so cost analytics survive admin changing
            // the workspace's default provider later.
            $table->string('provider', 32);
            $table->string('model', 64);
            $table->unsignedInteger('tokens_in')->default(0);
            $table->unsignedInteger('tokens_out')->default(0);
            $table->decimal('cost_usd', 10, 6)->default(0);

            $table->timestamps();

            // Insights dashboard filters by workspace + date.
            $table->index(['workspace_id', 'created_at']);
            // Knowledge gaps report = where was_fallback = 1.
            $table->index(['workspace_id', 'was_fallback']);
            // Confidence histogram on the dashboard.
            $table->index(['workspace_id', 'confidence']);
        });
    }

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