import { jsonError, jsonResponse } from "../../../common.js";

export async function onRequestGet(context: RequestContext) {
  const url = new URL(context.request.url);
  const month = parseInt(url.searchParams.get("month") ?? "");
  const year = parseInt(url.searchParams.get("year") ?? "");

  if (isNaN(month) || isNaN(year))
    return jsonError("Invalid month or year", 400);

  const currentYear = new Date().getUTCFullYear();
  const currentMonth = new Date().getUTCMonth() + 1;

  if (currentYear < year || (currentYear === year && currentMonth < month))
    return jsonError("Cannot get events for a time in the future", 400);

  const eventRecords = await context.data.prisma.event.findMany({
    select: {
      answer: true,
      approved: true,
      created_by: true,
      day: true,
      details: true,
      month: true,
      pending: true,
      performed_at: true,
      type: true,
      year: true,
    },
    where: {
      month: month,
      year: year,
    },
    orderBy: {
      day: "asc",
    },
  });

  return jsonResponse(JSON.stringify(eventRecords));
}
