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

export async function onRequestDelete(context: RequestContext) {
  const targetId = context.params.id as string;

  if (targetId.search(/^\d{16.19}$/) === -1)
    return jsonError("Invalid target id", 400);

  await context.data.prisma.appealBan.delete({
    where: {
      user: targetId,
    },
  });

  const { current_user: currentUser } = context.data;

  await fetch(context.env.APPEALS_WEBHOOK, {
    body: JSON.stringify({
      embeds: [
        {
          title: "User Unblocked",
          color: 3756250,
          description: `User ${targetId} is no longer blocked from the appeal form.`,
          fields: [
            {
              name: "Moderator",
              value: `${currentUser.username} (${currentUser.id})`,
            },
          ],
        },
      ],
    }),
    headers: {
      "content-type": "application/json",
    },
    method: "POST",
  });

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

export async function onRequestPost(context: RequestContext) {
  const { current_user: currentUser } = context.data;
  const targetId = context.params.id as string;

  if (targetId.search(/^\d{16,19}$/) === -1)
    return jsonError("Invalid target id", 400);

  await context.data.prisma.appealBan.create({
    data: {
      created_by: context.data.current_user.id,
      user: targetId,
    },
  });

  await fetch(context.env.APPEALS_WEBHOOK, {
    body: JSON.stringify({
      embeds: [
        {
          title: "User Blocked",
          color: 3756250,
          description: `User ${targetId} was blocked from the appeal form.`,
          fields: [
            {
              name: "Moderator",
              value: `${currentUser.username} (${currentUser.id})`,
            },
          ],
        },
      ],
    }),
    headers: {
      "content-type": "application/json",
    },
    method: "POST",
  });

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