import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import {
  answerRagQuery,
  isKnowledgePlatform,
  loadKnowledgeCatalog,
  type KnowledgePlatform,
} from "@/lib/rag";

export async function POST(request: Request) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = (await request.json()) as {
    platform?: string;
    question?: string;
    /** @deprecated alias — prefer `question` */
    query?: string;
    projectContext?: string;
    projectId?: string;
  };

  const platform = body.platform?.trim().toLowerCase() ?? "";
  if (!isKnowledgePlatform(platform)) {
    return NextResponse.json(
      {
        error:
          "Invalid platform. Use facebook, linkedin, instagram, youtube, twitter, tiktok, threads, pinterest, or global.",
      },
      { status: 400 },
    );
  }

  const question = (body.question ?? body.query)?.trim() ?? "";
  if (!question) {
    return NextResponse.json({ error: "question is required" }, { status: 400 });
  }

  try {
    const result = await answerRagQuery({
      platform: platform as KnowledgePlatform,
      question,
      projectContext: body.projectContext,
    });

    return NextResponse.json({
      answer: result.answer,
      provider: result.provider,
      model: result.model,
      platform: result.platform,
      citations: result.citations,
      projectId: body.projectId ?? null,
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : "RAG query failed";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

export async function GET() {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const catalog = await loadKnowledgeCatalog();
  return NextResponse.json({
    enabled: process.env.RAG_ENABLED !== "false",
    catalog,
    queryEndpoint: "/api/rag/query",
    reindexEndpoint: "/api/rag/reindex",
  });
}
