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

export async function onRequestGet(context: RequestContext) {
  const { current_user: currentUser } = context.data;

  if (
    !currentUser.email ||
    (await context.env.DATA.get("appeal_disabled")) ||
    (await context.data.prisma.appeal.findFirst({
      where: {
        approved: null,
        user: currentUser.id,
      },
    })) ||
    (await context.env.DATA.get(`blockedappeal_${currentUser.id}`))
  )
    return jsonResponse('{"can_appeal":false}');

  return jsonResponse('{"can_appeal":true}');
}

export async function onRequestPost(context: RequestContext) {
  if (await context.env.DATA.get("appeal_disabled"))
    return jsonError("Appeals are disabled", 403);

  const { learned, senderTokenId, whyBanned, whyUnban } = context.data.body;

  if (
    typeof learned !== "string" ||
    typeof whyBanned !== "string" ||
    typeof whyUnban !== "string" ||
    !learned.length ||
    learned.length > 2000 ||
    !whyBanned.length ||
    whyBanned.length > 500 ||
    !whyUnban.length ||
    whyUnban.length > 2000
  )
    return jsonError("One or more fields are missing or invalid", 400);

  const { current_user: currentUser } = context.data;

  if (!currentUser.email) return jsonError("No email for this session", 403);

  const existingBlockedAppeal = await context.env.DATA.get(
    `blockedappeal_${currentUser.id}`,
  );

  if (
    existingBlockedAppeal ||
    (await context.data.prisma.appeal.findFirst({
      where: {
        approved: null,
        user: {
          path: "id",
          equals: currentUser.id,
        },
      },
    }))
  )
    return jsonError("Appeal already submitted", 403);

  if (
    await context.data.prisma.appealBan.findUnique({
      where: {
        user: currentUser.id,
      },
    })
  ) {
    await context.env.DATA.put(`blockedappeal_${currentUser.id}`, "1", {
      metadata: { email: currentUser.email },
    });

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

  const appealId = `${currentUser.id}${Date.now()}${crypto
    .randomUUID()
    .replaceAll("-", "")}`;

  await context.data.prisma.appeal.create({
    data: {
      ban_reason: whyBanned,
      id: appealId,
      learned,
      reason_for_unban: whyUnban,
      user: {
        email: currentUser.email,
        id: currentUser.id,
        username: currentUser.username,
      },
    },
  });

  if (typeof senderTokenId === "string") {
    await context.data.prisma.pushNotification.create({
      data: {
        event_id: appealId,
        event_type: "appeal",
        token: senderTokenId,
      },
    });
  }

  await fetch(context.env.APPEALS_WEBHOOK, {
    body: JSON.stringify({
      embeds: [
        {
          title: "Appeal Submitted",
          color: 3756250,
          description: `View this appeal at https://carcrushers.cc/mod-queue?id=${appealId}&type=appeal`,
          fields: [
            {
              name: "Submitter",
              value: `${currentUser.username} (${currentUser.id})`,
            },
          ],
        },
      ],
    }),
    headers: {
      "content-type": "application/json",
    },
    method: "POST",
  });

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