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

export async function onRequestPost(context: RequestContext) {
  const { appeal } = context.data;
  const body = new FormData();
  body.append("from", "noreply@mail.carcrushers.cc");
  body.append("to", appeal.user.email);
  body.append("subject", "Appeal Accepted");
  body.append("template", "appeal_accepted");
  body.append("v:note", context.data.body.feedback || "No note provided.");

  const emailReq = await fetch(
    "https://api.mailgun.net/v3/mail.carcrushers.cc/messages",
    {
      body,
      headers: {
        authorization: `Basic ${btoa("api:" + context.env.MAILGUN_API_KEY)}`,
      },
      method: "POST",
    },
  );

  if (!emailReq.ok) {
    console.log(await emailReq.json());
    return jsonError("Failed to accept appeal", 500);
  }

  const { current_user: currentUser } = context.data;

  await context.env.D1.prepare("UPDATE appeals SET open = 0 WHERE id = ?;")
    .bind(context.params.id)
    .run();

  await fetch(
    `https://discord.com/api/v10/guilds/242263977986359297/bans/${appeal.id}`,
    {
      headers: {
        authorization: `Bot ${context.env.BOT_TOKEN}`,
        "x-audit-log-reason": `Appeal accepted by ${currentUser.username} (${currentUser.id})`,
      },
      method: "DELETE",
    },
  );

  await fetch(context.env.APPEALS_WEBHOOK, {
    body: JSON.stringify({
      embeds: [
        {
          title: "Appeal Accepted",
          color: 0x00ff00,
          description: `Appeal from user ${appeal.user.username} (${appeal.user.id}) was accepted.`,
          fields: [
            {
              name: "Moderator",
              value: `${currentUser.username} (${currentUser.id})`,
            },
          ],
        },
      ],
    }),
    headers: {
      "content-type": "application/json",
    },
    method: "POST",
  });

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