import { API_BASE_URL } from "../App";
import { b64e } from "./trash";

export async function makeRequest(
  url: string,
  params?:
    | string
    | Record<string, string>
    | string[][]
    | URLSearchParams
    | undefined
) {
  try {
    const req = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams(params).toString(),
    });

    return req.ok &&
      req.headers.get("Content-Type")?.includes("application/json")
      ? [1, await req.json()]
      : [req.status, await req.text()];
  } catch (err) {
    return [-1, err];
  }
}

export function LoginReq(pass: string) {
  return makeRequest(API_BASE_URL + "?login", { pass });
}

export function ServerReq(pass: string) {
  return makeRequest(API_BASE_URL + "?server", { pass });
}

export function ServerBlockReq(pass: string, block: boolean) {
  return makeRequest(API_BASE_URL + "?server", {
    pass,
    action: block ? "disable" : "enable",
  });
}
export function ServerMsgBlockReq(pass: string, value: string) {
  return makeRequest(API_BASE_URL + "?server", {
    pass,
    action: "update_block_message",
    value,
  });
}

export function ClassesReq(pass: string) {
  return makeRequest(API_BASE_URL + "?class", { pass });
}

export function ClassReq(pass: string, classId: string) {
  return makeRequest(API_BASE_URL + "?class", { pass, classId });
}

export function ClassUpdateNameReq(
  pass: string,
  classId: string,
  value: string
) {
  return makeRequest(API_BASE_URL + "?class", {
    pass,
    classId,
    action: "update_name",
    value,
  });
}

export function CreateClassReq(
  pass: string,
  classId: string,
  className: string
) {
  return makeRequest(API_BASE_URL + "?class", {
    pass,
    classId,
    action: "create",
    value: className,
  });
}

export function DELETEClassRequest(pass: string, classId: string) {
  return makeRequest(API_BASE_URL + "?class", {
    pass,
    classId,
    action: "DELETE",
  });
}

export function AdminUpdateReq(
  pass: string,
  adminId: string,
  action: "level" | "name",
  value: string
) {
  return makeRequest(API_BASE_URL + "?admin", {
    pass,
    adminId,
    action: "update_" + action,
    value,
  });
}

export function AdminRemoveReq(pass: string, adminId: string) {
  return makeRequest(API_BASE_URL + "?admin", {
    pass,
    adminId,
    action: "DELETE",
  });
}

export function AdminCreateReq(
  pass: string,
  classId: string,
  adminId: string,
  adminName: string,
  adminPrems: string
) {
  return makeRequest(API_BASE_URL + "?class", {
    pass,
    classId,
    action: "create_admin",
    value: `${adminId};${b64e(adminName)};${adminPrems}`,
  });
}
