import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { env } from "../config/env.js";

const key = () => Buffer.from(env.APP_ENCRYPTION_KEY, "hex");
export function encrypt(text: string): string {
  const iv = randomBytes(12), c = createCipheriv("aes-256-gcm", key(), iv), body = Buffer.concat([c.update(text, "utf8"), c.final()]);
  return Buffer.concat([iv, c.getAuthTag(), body]).toString("base64");
}
export function decrypt(data: string): string {
  const b = Buffer.from(data, "base64"), d = createDecipheriv("aes-256-gcm", key(), b.subarray(0, 12));
  d.setAuthTag(b.subarray(12, 28));
  return Buffer.concat([d.update(b.subarray(28)), d.final()]).toString("utf8");
}
export const sha256 = (s: string | Buffer) => createHash("sha256").update(s).digest("hex");
/** For short codes: keyed, so a leaked table cannot be reversed by trying a million codes. */
export const keyed = (s: string) => createHmac("sha256", key()).update(s).digest("hex");
export const randomToken = () => randomBytes(32).toString("base64url");
export const sameHash = (a: string, b: string) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
const B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
export const newTotpSecret = () => [...randomBytes(20)].map((b) => B32[b % 32]).join("");
export function totp(secret: string, at = Date.now(), step = 0): string {
  let bits = "";
  for (const ch of secret) bits += B32.indexOf(ch).toString(2).padStart(5, "0");
  const bytes = Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2)));
  const counter = Buffer.alloc(8);
  counter.writeBigUInt64BE(BigInt(Math.floor(at / 30_000) + step));
  const h = createHmac("sha1", bytes).update(counter).digest(), o = h[19]! & 15;
  return String((h.readUInt32BE(o) & 0x7fffffff) % 1_000_000).padStart(6, "0");
}
export const totpOk = (secret: string, code: string, at = Date.now()) => [-1, 0, 1].some((s) => sameHash(totp(secret, at, s), code));
