import { NextRequest, NextResponse } from "next/server";
import { resolveCaller } from "@/lib/auth";

const BACKEND_URL =
  process.env.BACKEND_URL || "https://aicommand.youngengineers.org";

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { question, thread_id } = body;

    if (!question) {
      return NextResponse.json(
        { error: "Missing required field: question" },
        { status: 400 },
      );
    }

    const { userId: user_id, token: callerToken } = resolveCaller(
      req,
      body.user_id,
    );

    if (!user_id || !callerToken) {
      return NextResponse.json(
        { error: "Missing user authentication" },
        { status: 401 },
      );
    }

    // Forward the resolved caller token (real portal-user hub JWT when
    // available, else the shared fallback) — aicommand relays this straight
    // to hub's /ai/key + /ai/usage, so this is what determines who gets
    // billed for this request on the hub side.
    const response = await fetch(`${BACKEND_URL}/api/portal-chatbot-rag-latest`, {
      method: "POST",
      headers: {
        accept: "application/json",
        "Content-Type": "application/json",
        Authorization: `Bearer ${callerToken}`,
      },
      body: JSON.stringify({
        question,
        user_id,
        thread_id,
      }),
    });

    const data = await response.json();
    if (!response.ok) {
      return NextResponse.json(
        { error: data.error || data.detail || "Failed to ask question" },
        { status: response.status },
      );
    }

    return NextResponse.json(data);
  } catch (error) {
    console.error("Error asking question:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
