import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
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;
      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: body.includePnt === true,
      force: body.force === true,
    });

    return NextResponse.json({ ok: true, payload });
  } catch (error) {
    return NextResponse.json(
      {
        error: error instanceof Error ? error.message : "No se pudo ejecutar el sync de licitaciones.",
      },
      { status: 400 },
    );
  }
}
