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

export async function onRequestPost(context: RequestContext) {
  const { day, details, type } = context.data.body;
  const now = new Date();
  const currentMonth = now.getUTCMonth() + 1;
  const currentYear = now.getUTCFullYear();
  const lastDayOfMonth = new Date(currentYear, currentMonth, 0).getUTCDate();

  if (
    typeof day !== "number" ||
    day < 1 ||
    // Last day of that month
    day > lastDayOfMonth ||
    // Stop people sending weird decimal days
    parseInt(day.toString()) !== day ||
    typeof details !== "string" ||
    !details.length ||
    !["fotd", "gamenight", "rotw", "qotd"].includes(type) ||
    (type === "rotw" && !context.data.body.answer)
  )
    return jsonError("Invalid body", 400);

  if (
    await context.data.prisma.event.findFirst({
      select: {
        id: true,
      },
      where: {
        OR: [{ approved: true }, { pending: true }],
        day,
        month: currentMonth,
        type,
        year: currentYear,
      },
    })
  )
    return jsonError(
      "Event with that type already exists for the specified date",
      400,
    );

  if (type === "rotw") {
    const weekRanges: { [k: number]: number } = {
      0: 7,
      1: 14,
      2: 21,
      3: 28,
      4: 35,
    };

    const weekRange = Math.floor(day / 7);

    const existingEventInRange = await context.data.prisma.event.findFirst({
      select: {
        id: true,
      },
      where: {
        OR: [{ approved: true }, { pending: true }],
        day: {
          gte: weekRanges[weekRange] - 7,
          lte: weekRanges[weekRange],
        },
        month: currentMonth,
        type: "rotw",
        year: currentYear,
      },
    });

    if (existingEventInRange)
      return jsonError("There is already an rotw for that week", 400);
  }

  const id = `${now.getTime()}${crypto.randomUUID().replaceAll("-", "")}`;

  await context.data.prisma.event.create({
    data: {
      answer: context.data.body.answer || null,
      approved: type === "gamenight",
      created_by: context.data.current_user.id,
      day,
      details,
      id,
      month: currentMonth,
      pending: type !== "gamenight",
      type,
      year: currentYear,
    },
  });

  await fetch(context.env.EVENTS_WEBHOOK, {
    body: JSON.stringify({
      embeds: [
        {
          title: "Event Submitted",
          color: 3756250,
          description: `${context.data.current_user.username} submitted an event for ${currentYear}-${currentMonth}-${day}. See it at https://carcrushers.cc/events-team`,
        },
      ],
    }),
    headers: {
      "content-type": "application/json",
    },
    method: "POST",
  });

  if (type !== "gamenight")
    await context.env.DATA.put(
      `eventemail_${id}`,
      JSON.stringify({ email: context.data.current_user.email, type }),
      { expirationTtl: 2678400 },
    );

  return new Response(null, {
    status: 204,
  });
}
