<?php

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

/**
 * Adds Knowledge Agent metadata to messages so the actual channel
 * senders (email SMTP, WhatsApp/IG/FB REST APIs, web widget JSON
 * response) can render citations + thumbs UI without re-running the
 * AI pipeline.
 *
 *   ai_was_fallback     — set when AIManager substituted the canned
 *                         "I don't know" message for a low-confidence
 *                         LLM answer. Senders can suppress citations
 *                         + thumbs when true (no real answer to rate).
 *
 *   ai_feedback_token   — opaque signed token bound to the kb_query_logs
 *                         row that this Message is the customer-facing
 *                         half of. Channel renderers turn this into a
 *                         /kb/feedback/{token}/{up|down} link.
 *
 *   ai_cited_sources    — structured array of {index, title, url,
 *                         document_id} per cited chunk. Lets each
 *                         channel render a footer formatted for its
 *                         medium (HTML <ul> for email, plain text for
 *                         WhatsApp, interactive list for widget).
 *
 *   ai_original_content — the raw LLM output when fallback substitution
 *                         fired. Stored separately so the admin can
 *                         audit what the agent actually said even
 *                         though the customer saw the canned message.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('messages', function (Blueprint $table) {
            $table->boolean('ai_was_fallback')->nullable()->after('ai_sources_used');
            $table->string('ai_feedback_token', 64)->nullable()->after('ai_was_fallback');
            $table->json('ai_cited_sources')->nullable()->after('ai_feedback_token');
            $table->text('ai_original_content')->nullable()->after('ai_cited_sources');
        });
    }

    public function down(): void
    {
        Schema::table('messages', function (Blueprint $table) {
            $table->dropColumn([
                'ai_was_fallback',
                'ai_feedback_token',
                'ai_cited_sources',
                'ai_original_content',
            ]);
        });
    }
};
