const DATASTORE_URL =
  "https://apis.roblox.com/cloud/v2/universes/274816972/data-stores/BanData/entries/CloudBanList";

const MESSAGING_SERVICE_URL =
  "https://apis.roblox.com/cloud/v2/universes/274816972:publishMessage";

const SAVE_DATA_URL =
  "https://apis.roblox.com/cloud/v2/universes/274816972/data-stores/RealData/entries";

export async function getBanList(context: RequestContext) {
  const data = await fetch(DATASTORE_URL, {
    headers: {
      "x-api-key": context.env.ROBLOX_OPENCLOUD_KEY,
    },
  });

  if (!data.ok) {
    console.log(await data.json());
    throw new Error("Failed to retrieve ban list");
  }

  return (await data.json()) as {
    etag: string;
    path: string;
    value: {
      [k: string]: {
        BanType: number;
        hidden_from_leaderboards?: boolean;
        serverconfigurator_blacklist?: boolean;
        Unbanned?: boolean;
        UnbanReduct?: number;
      };
    };
  };
}

export async function publishMessage(
  context: RequestContext,
  topic: string,
  message: string,
) {
  const response = await fetch(MESSAGING_SERVICE_URL, {
    body: JSON.stringify({
      message,
      topic,
    }),
    headers: {
      "Content-Type": "application/json",
      "x-api-key": context.env.ROBLOX_OPENCLOUD_KEY,
    },
    method: "POST",
  });

  if (!response.ok) {
    throw new Error("Failed to publish message\n" + (await response.text()));
  }
}

export async function getSaveData(
  context: RequestContext,
  user: number,
): Promise<string> {
  const data = await fetch(`${SAVE_DATA_URL}/${user}`, {
    headers: {
      "x-api-key": context.env.ROBLOX_OPENCLOUD_KEY,
    },
  });

  if (!data.ok) {
    console.log(await data.json());
    throw new Error(`Failed to retrieve save data for ${user}`);
  }

  return ((await data.json()) as { value: string }).value;
}

export async function setBanList(
  context: RequestContext,
  value: any,
  etag?: string,
) {
  const setRequest = await fetch(DATASTORE_URL, {
    body: JSON.stringify({
      etag,
      value,
    }),
    headers: {
      "content-type": "application/json",
      "x-api-key": context.env.ROBLOX_OPENCLOUD_KEY,
    },
    method: "PATCH",
  });

  if (!setRequest.ok) {
    console.log(await setRequest.json());
    throw new Error("Failed to set ban list");
  }

  return await setRequest.json();
}
