export async function generateSecretKey() {
  const key = await crypto.subtle.generateKey(
    { name: "HMAC", hash: "SHA-512" },
    true,
    ["sign", "verify"],
  );

  return key;
}

let cacheKey: CryptoKey | undefined;
let previousKey = "invalid";

export async function prepareSecretKey() {
  const key = Deno.env.get("SECRET_KEY");
  if (key === previousKey) {
    return cacheKey!;
  }
  if (key) {
    const jwk = JSON.parse(key) as JsonWebKey;
    previousKey = key;
    {
      const key = await crypto.subtle.importKey(
        "jwk",
        jwk,
        { name: "HMAC", hash: "SHA-512" },
        true,
        ["sign", "verify"],
      );
      cacheKey = key;
      return key;
    }
  } else {
    const key = await generateSecretKey();
    const out = await crypto.subtle.exportKey("jwk", key);
    const outStr = JSON.stringify(out);
    Deno.env.set("SECRET_KEY", outStr);
    cacheKey = key;
    previousKey = outStr;
    return key;
  }
}
