import { NextResponse } from "next/server";
import { runPeriodicNormativeVerification } from "@/lib/compliance/regulations";
import { isAuthorizedCronRequest } from "@/lib/cron/auth";
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;
}

async function runSync(request: Request) {
  if (!isAuthorizedCronRequest(request)) {
    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 includeLicitaya = parseBoolean(url.searchParams.get("include_licitaya"));
  const includeRegulations = parseBoolean(url.searchParams.get("include_regulations"));
  const force = parseBoolean(url.searchParams.get("force"));
  const payload = await runDailyLicitationsSync({ municipalityId, limit, skip, targetYear, includePnt, includeLicitaya, force });
  let regulations = null;
  let regulationsError: string | null = null;

  if (includeRegulations !== false) {
    try {
      regulations = await runPeriodicNormativeVerification(new Date());
    } catch (error) {
      regulationsError = error instanceof Error ? error.message : "No fue posible verificar reglamentos oficiales.";
    }
  }

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

export async function GET(request: Request) {
  return runSync(request);
}

export async function POST(request: Request) {
  return runSync(request);
}
