import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { runPeriodicNormativeVerification } from "@/lib/compliance/regulations";
import { runDailyLicitationsSync } from "@/lib/licitations/sync";

export const runtime = "nodejs";

export async function POST(request: Request) {
  const user = await requireAdminApiUser();

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

  try {
    const body = (await request.json().catch(() => ({}))) as {
      municipalityId?: string;
      limit?: number;
      skip?: number;
      targetYear?: number;
      includePnt?: boolean;
      includeLicitaya?: boolean;
      includeRegulations?: boolean;
      force?: boolean;
    };

    const payload = await runDailyLicitationsSync({
      municipalityId: typeof body.municipalityId === "string" ? body.municipalityId : undefined,
      limit: typeof body.limit === "number" ? body.limit : undefined,
      skip: typeof body.skip === "number" ? body.skip : undefined,
      targetYear: typeof body.targetYear === "number" ? body.targetYear : undefined,
      includePnt: typeof body.includePnt === "boolean" ? body.includePnt : undefined,
      includeLicitaya: typeof body.includeLicitaya === "boolean" ? body.includeLicitaya : undefined,
      force: typeof body.force === "boolean" ? body.force : undefined,
    });
    const includeRegulations = body.includeRegulations !== false;
    let regulations = null;
    let regulationsError: string | null = null;

    if (includeRegulations) {
      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 });
  } catch (error) {
    return NextResponse.json(
      {
        error: error instanceof Error ? error.message : "No se pudo ejecutar el sync de licitaciones.",
      },
      { status: 400 },
    );
  }
}
