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

export async function onRequestPost(context: RequestContext) {
  const { D1 } = context.env;
  const { event, prisma } = context.data;

  try {
    const row = await prisma.event.findUnique({
      select: {
        performed_at: true,
      },
      where: {
        id: event.id,
      },
    });

    if (row?.performed_at instanceof Date)
      return jsonError("Event already marked as completed or forgotten", 400);

    await D1.batch([
      D1.prepare(
        "UPDATE events SET performed_at = datetime(0, 'unixepoch') WHERE id = ?;",
      ).bind(event.id),
      D1.prepare(
        "UPDATE et_members SET points = points - 5 WHERE id = ?;",
      ).bind(event.created_by),
    ]);
  } catch (e) {
    console.log(e);

    return jsonError("Failed to complete batch transaction", 500);
  }

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