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

export async function onRequestPost(context: RequestContext) {
  if (context.data.event.reached_minimum_player_count)
    return jsonError("This event is already certified", 400);

  const { D1 } = context.env;

  await D1.exec("BEGIN TRANSACTION;");

  try {
    const row = await D1.prepare(
      "UPDATE events SET reached_minimum_player_count = 1 WHERE id = ? RETURNING created_by;",
    )
      .bind(context.data.event.id)
      .first();

    if (!row) {
      await D1.exec("ROLLBACK;");
      return jsonError("Event does not exist", 404);
    }

    await D1.prepare("UPDATE et_members SET points = points + 10 WHERE id = ?;")
      .bind(row.created_by)
      .run();
    await D1.exec("COMMIT;");
  } catch (e) {
    console.log(e);
    await D1.exec("ROLLBACK;");

    return jsonError(
      "Failed to certify event because the event or points could not be updated",
      500,
    );
  }

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