import { NextResponse } from "next/server";
import { getSessionPayload } from "@/lib/auth/session";
import { searchLicitations } from "@/lib/licitations/query";

function parsePositiveInt(value: string | null, fallback: number) {
  if (!value) {
    return fallback;
  }

  const parsed = Number.parseInt(value, 10);

  if (!Number.isFinite(parsed) || parsed < 0) {
    return fallback;
  }

  return parsed;
}

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 take = Math.min(parsePositiveInt(url.searchParams.get("take"), 50), 100);
  const skip = parsePositiveInt(url.searchParams.get("skip"), 0);

  const payload = await searchLicitations({
    state: url.searchParams.get("state"),
    municipality: url.searchParams.get("municipality"),
    procedureType: url.searchParams.get("procedure_type"),
    q: url.searchParams.get("q"),
    minAmount: url.searchParams.get("min_amount"),
    maxAmount: url.searchParams.get("max_amount"),
    dateFrom: url.searchParams.get("date_from"),
    dateTo: url.searchParams.get("date_to"),
    includeClosed: url.searchParams.get("include_closed") === "true",
    take,
    skip,
  });

  return NextResponse.json(payload);
}
