import { NextResponse } from "next/server";
import { getSessionPayload } from "@/lib/auth/session";
import { getAiEnhancedLicitationRecommendationsForUser } from "@/lib/licitations/ai-recommendations";

function parseTop(value: string | null) {
  if (!value) {
    return undefined;
  }

  const parsed = Number.parseInt(value, 10);
  return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
}

export async function GET(request: Request) {
  const session = await getSessionPayload();

  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const url = new URL(request.url);
  const profileId = url.searchParams.get("profileId") ?? url.searchParams.get("profile_id");
  const top = parseTop(url.searchParams.get("top"));
  const payload = await getAiEnhancedLicitationRecommendationsForUser(session.userId, {
    profileId,
    top,
  });

  return NextResponse.json({
    ok: true,
    ...payload,
  });
}
