import CryptoJS from "crypto-js";

export interface TurnCredentials {
  username: string;
  password: string;
  expire: number;
}

interface IceServer {
  urls: string | string[];
  username?: string;
  credential?: string;
}

const TURN_URLS: (string | string[])[] = ["turn:8.134.35.244:3478"];

function decryptTurn(dataBase64: string): TurnCredentials {
  const secret = "kuraa.cc";

  const raw = CryptoJS.enc.Base64.parse(dataBase64);

  const iv = CryptoJS.lib.WordArray.create(raw.words.slice(0, 4), 16);

  const ciphertext = CryptoJS.lib.WordArray.create(
    raw.words.slice(4),
    raw.sigBytes - 16,
  );

  const key = CryptoJS.MD5(secret);

  const decrypted = CryptoJS.AES.decrypt(
    { ciphertext: ciphertext } as CryptoJS.lib.CipherParams,
    key,
    {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    },
  );

  const result = decrypted.toString(CryptoJS.enc.Utf8);

  return JSON.parse(result);
}

export async function fetchTurnServers(name: string): Promise<IceServer[]> {
  const response = await fetch("https://kuraa.cc/api/rtc", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ name }),
  });

  if (!response.ok) {
    throw new Error(
      `TURN API error: ${response.status} ${response.statusText}`,
    );
  }

  const encryptedData: string = await response.text();

  const credentials: TurnCredentials = decryptTurn(encryptedData);

  if (!TURN_URLS.length) {
    console.warn("未配置 TURN 地址，请在 turn.ts 中配置 TURN_URLS");
    return [];
  }

  return TURN_URLS.map((urls) => ({
    urls,
    username: credentials.username,
    credential: credentials.password,
  }));
}
