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

export async function onRequestPost(context: RequestContext) {
  if (typeof context.data.body.approved !== "boolean")
    return jsonError("Decision type must be a boolean", 400);

  const updatedEvent = await context.data.prisma.event.update({
    data: {
      approved: context.data.body.approved,
      pending: false,
    },
    where: {
      id: context.data.event.id,
    },
  });

  if (!updatedEvent) return jsonError("This event does not exist", 404);

  const emailData: { email: string; type: string } | null =
    await context.env.DATA.get(`eventemail_${context.data.event.id}`, {
      type: "json",
    });

  const usernameData = await context.data.prisma.etMember.findUnique({
    where: {
      id: updatedEvent.created_by,
    },
    select: {
      name: true,
    },
  });

  if (emailData && usernameData) {
    await sendEmail(
      emailData.email,
      context.env.MAILGUN_API_KEY,
      `Event ${context.data.body.approved ? "Approved" : "Rejected"}`,
      `event_${context.data.body.approved ? "approved" : "rejected"}`,
      {
        date: `${updatedEvent.year}-${updatedEvent.month.toString().padStart(2, "0")}-${updatedEvent.day.toString().padStart(2, "0")}`,
        event: emailData.type,
        username: usernameData.name,
      },
    );
  }

  await context.env.DATA.delete(`eventemail_${context.data.event.id}`);

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