function base64ToUint8Array(base64String: string) {
  const binaryString = atob(base64String)
  const byteArray = new Uint8Array(binaryString.length)
  for (let i = 0; i < binaryString.length; i++) {
    byteArray[i] = binaryString.charCodeAt(i)
  }
  return byteArray
}

function utf8ToUint8Array(utf8String: string) {
  return new TextEncoder().encode(utf8String)
}

function uint8ArrayToUtf8(uint8Array: Uint8Array) {
  return new TextDecoder().decode(uint8Array)
}

export async function decryptData(
  keyBase64: string,
  ivBase64: string,
  encryptedDataBase64: string
): Promise<string> {
  const keyBuffer = await crypto.subtle.importKey(
    "raw",
    base64ToUint8Array(keyBase64),
    "AES-CBC",
    false,
    ["decrypt"]
  )

  const encryptedDataBuffer = base64ToUint8Array(encryptedDataBase64)
  const ivBuffer = base64ToUint8Array(ivBase64)
  const decryptedDataBuffer = await crypto.subtle.decrypt(
    { name: "AES-CBC", iv: ivBuffer },
    keyBuffer,
    encryptedDataBuffer
  )

  const decryptedData = uint8ArrayToUtf8(new Uint8Array(decryptedDataBuffer))
  return decryptedData
}
