export async function getJavaUuid(username: string) {
  const response = await fetch(`https://api.mojang.com/users/profiles/minecraft/${username}`);
  if (!response.ok) {
    // user doesn't exist
    if (response.status == 400 || response.status == 404) throw new Error();
    // rate limit
    else if (response.status == 429) return null;
    return null;
  }
  const json = await response.json();
  const id: string = json['id'];
  // prettier-ignore
  return `${id.substring(0, 8)}-${id.substring(8, 12)}-${id.substring(12, 16)}-${id.substring(16, 20)}-${id.substring(20)}`;
}

// https://github.com/carlop3333/XUIDGrabber/blob/main/grabber.js
export async function getBedrockUuid(username: string): Promise<string | null> {
  const initialPageResponse = await fetch('https://cxkes.me/xbox/xuid');
  const initialPageContent = await initialPageResponse.text();
  const token = /name="_token"\svalue="(?<token>\w+)"/.exec(initialPageContent)?.groups?.token;

  const cookies = initialPageResponse.headers.get('set-cookie')?.split(' ');
  if (token === undefined || cookies === undefined || cookies.length < 11) return null;

  const requestBody = new URLSearchParams();
  requestBody.set('_token', token);
  requestBody.set('gamertag', username);

  const resultPageResponse = await fetch('https://cxkes.me/xbox/xuid', {
    method: 'post',
    body: requestBody,
    // prettier-ignore
    headers: {
      'Host': 'www.cxkes.me',
      'Accept-Encoding': 'gzip, deflate,br',
      'Content-Length': Buffer.byteLength(requestBody.toString()).toString(),
      'Origin': 'https://www.cxkes.me',
      'DNT': '1',
      'Connection': 'keep-alive',
      'Referer': 'https://www.cxkes.me/xbox/xuid',
      'Cookie': `${cookies[0]} ${cookies[10].slice(0, cookies[10].length - 1)}`,
      'Upgrade-Insecure-Requests': '1',
      'Sec-Fectch-Dest': 'document',
      'Sec-Fetch-Mode': 'navigate',
      'Sec-Fetch-Site': 'same-origin',
      'Sec-Fetch-User': '?1',
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
      'Accept-Language': 'en-US,es;q=0.8,en-US;q=0.5,en;q=0.3',
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });
  const resultPageContent = await resultPageResponse.text();
  let xuid: string | undefined;
  if ((xuid = /id="xuidHex">(?<xuid>\w+)</.exec(resultPageContent)?.groups?.xuid) === undefined) throw new Error();
  return `00000000-0000-0000-${xuid.substring(0, 4)}-${xuid.substring(4)}`;
}
