/**
 * WhatsApp Knowledge Base Query API
 * POST /api/whatsapp/knowledge-base/query
 *
 * Queries company-specific knowledge base for relevant answers.
 * Called by n8n workflow when AI agent needs information.
 */

import { NextRequest, NextResponse } from "next/server";
import { queryKnowledgeBase } from "@/lib/services/whatsapp-knowledge-base.service";
import { KnowledgeBaseQuerySchema } from "@/lib/validators/whatsapp-ai.validator";
import { systemSettingsService } from "@/lib/services/system-settings.service";
import { PineconeMultimodalService } from "@/lib/services/pinecone-multimodal.service";
import { getDataSource } from "@/lib/data-source";
import { logger } from "@/lib/logger";
import { corsResponse } from "@/lib/cors";

export async function POST(request: NextRequest) {
  try {
    // Authenticate caller via n8n token
    const authHeader = request.headers.get("authorization");
    const token = authHeader?.replace("Bearer ", "");
    if (!token) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    const isValid = await systemSettingsService.validateN8NToken(token);
    if (!isValid) {
      return NextResponse.json({ error: "Invalid token" }, { status: 401 });
    }

    const body = await request.json();

    // Validate input
    const validation = KnowledgeBaseQuerySchema.safeParse(body);

    if (!validation.success) {
      return NextResponse.json(
        {
          error: "Invalid request",
          details: validation.error.errors,
        },
        { status: 400 },
      );
    }

    const query = validation.data;

    // ── Pinecone multimodal (primary when configured) ────────────────
    if (PineconeMultimodalService.isConfigured()) {
      try {
        const result = await PineconeMultimodalService.queryAndGenerate(
          query.organizationId,
          query.query,
          {
            language: query.language as "en" | "ar",
            topK: 5,
          },
        );

        return NextResponse.json({
          success: true,
          answer: result.answer,
          sources: result.citations,
          mediaUrls: (result.mediaResults || [])
            .filter((m) => m.type === "image" && m.url)
            .map((m) => m.url),
          metadata: {
            ...result.metadata,
            ragEngine: "pinecone-multimodal",
          },
        });
      } catch (pineconeError) {
        logger.warn("Pinecone query failed, falling back to legacy KB", {
          error: pineconeError,
          organizationId: query.organizationId,
        });
        // Fall through to Convex / Prisma paths
      }
    }

    // ── Convex data-source branch ──────────────────────────────────────
    if (getDataSource("whatsapp") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");

        // Fetch all active KB entries from Convex
        type KBEntry = {
          question: string;
          answer: string;
          category: string | null;
          language: string;
          priority: number;
        };

        const kbEntries = await convexQuery<KBEntry[]>(
          "whatsapp/queries:getKnowledgeBaseEntries",
          {
            organizationId: query.organizationId,
            language: query.language,
            limit: query.limit ?? 20,
          },
        );

        if (kbEntries && kbEntries.length > 0) {
          // Keyword match against Convex results (same logic as Prisma path)
          const keywords = query.query
            .toLowerCase()
            .split(/\s+/)
            .filter((w: string) => w.length >= 3)
            .slice(0, 10);

          const faqResults = (
            kbEntries as Array<{
              question: string;
              answer: string;
              category: string | null;
              language: string;
              priority: number;
            }>
          )
            .filter((entry) =>
              keywords.some((kw: string) =>
                entry.question.toLowerCase().includes(kw),
              ),
            )
            .slice(0, query.limit ?? 5)
            .map((entry) => ({
              source: "faq" as const,
              question: entry.question,
              answer: entry.answer,
              category: entry.category,
            }));

          // RAG results still come from Gemini (external API — not a DB operation)
          // Call the original queryKnowledgeBase for RAG only, then merge FAQ from Convex
          let ragResults: Array<{
            source: "gemini_rag" | "faq";
            answer?: string;
            citations?: Array<{ documentTitle: string; excerpt: string }>;
          }> = [];
          try {
            const fullResults = await queryKnowledgeBase(query);
            ragResults = fullResults.filter((r) => r.source === "gemini_rag");
          } catch {
            // RAG may fail — continue with FAQ-only results
          }

          const allResults = [...ragResults, ...faqResults];

          logger.info("KB query completed (Convex)", {
            organizationId: query.organizationId,
            language: query.language,
            ragResultsCount: ragResults.length,
            faqResultsCount: faqResults.length,
          });

          return NextResponse.json({
            success: true,
            data: {
              results: allResults,
              ragAnswer: ragResults[0]?.answer || null,
              ragCitations: ragResults[0]?.citations || [],
              faqMatches: faqResults,
              count: allResults.length,
              query: query.query,
            },
          });
        }
        // Empty Convex results → fall through to Prisma
      } catch (error) {
        console.error("[Convex fallback] whatsapp knowledge-base:", error);
        // Fall through to Prisma
      }
    }

    // ── Prisma path (primary or fallback) ──────────────────────────────
    // Query knowledge base (Gemini RAG + FAQ entries)
    const results = await queryKnowledgeBase(query);

    // Separate RAG and FAQ results for clarity
    const ragResults = results.filter((r) => r.source === "gemini_rag");
    const faqResults = results.filter((r) => r.source === "faq");

    logger.info("KB query completed", {
      organizationId: query.organizationId,
      language: query.language,
      ragResultsCount: ragResults.length,
      faqResultsCount: faqResults.length,
    });

    return NextResponse.json({
      success: true,
      data: {
        results,
        ragAnswer: ragResults[0]?.answer || null,
        ragCitations: ragResults[0]?.citations || [],
        faqMatches: faqResults,
        count: results.length,
        query: query.query,
      },
    });
  } catch (error) {
    logger.error("KB query error", { error });

    return NextResponse.json(
      {
        error: "Internal server error",
        message:
          error instanceof Error
            ? error.message
            : "Failed to query knowledge base",
      },
      { status: 500 },
    );
  }
}

// OPTIONS for CORS preflight
export async function OPTIONS() {
  return corsResponse("POST, OPTIONS");
}
