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

export async function onRequestDelete(context: RequestContext) {
  const eventId = context.params.id as string;
  const eventData = await context.env.D1.prepare(
    "SELECT created_by FROM events WHERE id = ?;",
  )
    .bind(eventId)
    .first();

  if (!eventData) return jsonError("No event exists with that ID", 404);

  const { current_user: currentUser } = context.data;

  if (
    eventData.created_by !== currentUser.id &&
    ![1 << 4, 1 << 12].find((int) => currentUser.permissions & int)
  )
    return jsonError("You are not authorized to delete that event", 403);

  await context.env.DATA.delete(`event_${eventId}`);
  await context.env.D1.prepare("DELETE FROM events WHERE id = ?;")
    .bind(eventId)
    .run();

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

export async function onRequestPatch(context: RequestContext) {
  const eventId = context.params.id as string;
  const { body } = context.data;
  const eventData = await context.env.D1.prepare(
    "SELECT answer, created_by, details FROM events WHERE id = ?;",
  )
    .bind(eventId)
    .first();

  if (!eventData) return jsonError("No event exists with that ID", 404);

  const { current_user: currentUser } = context.data;

  if (
    eventData.created_by !== currentUser.id &&
    ![1 << 4, 1 << 12].find((int) => currentUser.permissions & int)
  )
    return jsonError("You are not authorized to modify this event", 403);

  eventData.answer &&= body.answer;
  eventData.details &&= body.details;

  await context.env.D1.prepare(
    "UPDATE events SET answer = ?, details = ? WHERE id = ?;",
  )
    .bind(eventData.answer, eventData.details, eventId)
    .run();

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

export async function onRequestPost(context: RequestContext) {
  const eventId = context.params.id as string;
  const eventData = await context.env.D1.prepare(
    "SELECT approved, performed_at FROM events WHERE id = ?;",
  )
    .bind(eventId)
    .first();

  if (!eventData) return jsonError("No event exists with that ID", 404);

  if (!eventData.approved)
    return jsonError("Cannot perform unapproved event", 403);

  await context.env.D1.prepare(
    "UPDATE events SET performed_at = ? WHERE id = ?;",
  )
    .bind(Date.now(), eventId)
    .run();

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