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

export async function onRequest(context: RequestContext) {
  const pathSegments = new URL(context.request.url).pathname.split("/");

  // Skip checks for the by-id endpoint
  if (pathSegments.length <= 5) return await context.next();

  const eventInfo = await context.env.D1.prepare(
    "SELECT * FROM events WHERE id = ?;",
  )
    .bind(context.params.id)
    .first();

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

  if (![1 << 4, 1 << 12].find((p) => context.data.current_user.permissions & p))
    return jsonError("You cannot manage this event.", 403);

  context.data.event = eventInfo;

  return await context.next();
}