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: Record<string, number | string> | null =
    await context.env.D1.prepare(
      "UPDATE events SET approved = ?, pending = 0 WHERE id = ? RETURNING created_by, day, month, year;",
    )
      .bind(Number(context.data.body.approved), context.data.event.id)
      .first();

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

  const email = await context.env.DATA.get(
    `eventemail_${context.data.event.id}`,
  );
  const usernameData: Record<string, string> | null =
    await context.env.D1.prepare("SELECT name FROM et_members WHERE id = ?;")
      .bind(updatedEvent.created_by)
      .first();

  if (email && usernameData) {
    await sendEmail(
      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")}`,
        username: usernameData.name,
      },
    );
  }

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

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