import { jsonError } from "../../../common.js";
import sendEmail from "../../../email.js";
import { sendPushNotification } from "../../../gcloud.js";

export async function onRequestPost(context: RequestContext) {
  const { appeal, fcm_token } = context.data;

  if (fcm_token) {
    await sendPushNotification(
      context.env,
      "Appeal Accepted",
      context.data.body.feedback || "No additional details to display",
      fcm_token,
    );

    await context.data.prisma.pushNotification.delete({
      where: {
        event_id: appeal.id,
        event_type: "appeal",
      },
    });
  } else {
    const emailResponse = await sendEmail(
      appeal.user.email,
      context.env.MAILGUN_API_KEY,
      "Appeal Accepted",
      "appeal_accepted",
      {
        note: context.data.body.feedback || "No note provided.",
      },
    );

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

  const { current_user: currentUser } = context.data;

  await context.data.prisma
    .$executeRaw`UPDATE appeals SET approved = TRUE, user = json_remove(user, '$.id') WHERE id = ${appeal.id};`;

  await fetch(
    `https://discord.com/api/v10/guilds/242263977986359297/bans/${appeal.user.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: 65280,
          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,
  });
}
