import { NextResponse } from "next/server";
import { licitationsConfig } from "@/lib/licitations/config";
import { runDailyLicitationsSync } from "@/lib/licitations/sync";

export const runtime = "nodejs";

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

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

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

  const normalized = value.trim().toLowerCase();

  if (["1", "true", "yes", "si"].includes(normalized)) {
    return true;
  }

  if (["0", "false", "no"].includes(normalized)) {
    return false;
  }

  return undefined;
}

export async function POST(request: Request) {
  const token = request.headers.get("x-sync-token") ?? "";

  if (!licitationsConfig.syncCronToken || token !== licitationsConfig.syncCronToken) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const url = new URL(request.url);
  const municipalityId = url.searchParams.get("municipality_id") ?? undefined;
  const limit = parsePositiveInt(url.searchParams.get("limit"));
  const skip = parsePositiveInt(url.searchParams.get("skip"));
  const targetYear = parsePositiveInt(url.searchParams.get("target_year"));
  const includePnt = parseBoolean(url.searchParams.get("include_pnt"));
  const force = parseBoolean(url.searchParams.get("force"));
  const payload = await runDailyLicitationsSync({ municipalityId, limit, skip, targetYear, includePnt, force });

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