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

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

// Forwards the resolved caller token (real portal-user hub JWT when
// available, else the shared fallback) — aicommand relays this to hub's
// /ai/key + /ai/usage for per-user billing attribution.
function backendHeaders(token: string, extra: Record<string, string> = {}) {
  return {
    ...extra,
    Authorization: `Bearer ${token}`,
  };
}

export async function POST(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const { userId: user_id, token: callerToken } = resolveCaller(
      req,
      searchParams.get("user_id"),
    );

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

    // Call backend to create thread
    const response = await fetch(`${BACKEND_URL}/api/threads?user_id=${user_id}`, {
      method: "POST",
      headers: backendHeaders(callerToken, {
        "accept": "application/json",
        "Content-Type": "application/json",
      }),
      body: JSON.stringify({
        title: "",
        user_id: user_id,
      }),
    });

    const data = await response.json();

    if (!response.ok) {
      console.error("Backend error:", data, "Status:", response.status);
      return NextResponse.json(
        { error: data.error || "Failed to create thread", data },
        { status: response.status }
      );
    }

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

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const { userId: user_id, token: callerToken } = resolveCaller(
      req,
      searchParams.get("user_id"),
    );
    const limit = searchParams.get("limit") || "20";

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

    // Call backend to get user threads
    const response = await fetch(
      `${BACKEND_URL}/api/threads/user/${user_id}?limit=${limit}`,
      {
        method: "GET",
        headers: backendHeaders(callerToken, {
          "accept": "application/json",
        }),
      }
    );

    const data = await response.json();

    if (!response.ok) {
      console.error("Backend error:", data, "Status:", response.status);
      return NextResponse.json(
        { error: data.error || "Failed to fetch threads", data },
        { status: response.status }
      );
    }

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