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

/**
 * Authenticator-app codes (RFC 6238 TOTP, the scheme Google Authenticator,
 * Microsoft Authenticator, Authy and 1Password all use): HMAC-SHA1, six
 * digits, a new code every 30 seconds. Built on node:crypto, no dependency.
 *
 * The shared secret is stored encrypted (AES-256-GCM) under TOTP_ENCRYPTION_KEY,
 * or a key derived from JWT_REFRESH_SECRET when that is unset — so a copied
 * database alone cannot mint codes. Recovery codes are stored only as HMACs.
 */

const STEP_SECONDS = 30;
const DIGITS = 6;
/** Accept the code before and after the current one: phone clocks drift. */
const WINDOW = 1;
const B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

export function base32Encode(buf: Buffer): string {
  let bits = 0;
  let value = 0;
  let out = '';
  for (const byte of buf) {
    value = (value << 8) | byte;
    bits += 8;
    while (bits >= 5) {
      out += B32[(value >>> (bits - 5)) & 31];
      bits -= 5;
    }
  }
  if (bits > 0) out += B32[(value << (5 - bits)) & 31];
  return out;
}

export function base32Decode(s: string): Buffer {
  const clean = s.toUpperCase().replace(/[^A-Z2-7]/g, '');
  let bits = 0;
  let value = 0;
  const out: number[] = [];
  for (const ch of clean) {
    value = (value << 5) | B32.indexOf(ch);
    bits += 5;
    if (bits >= 8) {
      out.push((value >>> (bits - 8)) & 255);
      bits -= 8;
    }
  }
  return Buffer.from(out);
}

/** A new 160-bit secret, Base32 — what the authenticator app stores. */
export const newTotpSecret = () => base32Encode(randomBytes(20));

export const stepOf = (now = Date.now()) => Math.floor(now / 1000 / STEP_SECONDS);

/** The code for one 30-second step (RFC 4226 dynamic truncation). */
export function codeAt(secretB32: string, step: number): string {
  const counter = Buffer.alloc(8);
  counter.writeBigUInt64BE(BigInt(step));
  const mac = createHmac('sha1', base32Decode(secretB32)).update(counter).digest();
  const off = mac[mac.length - 1] & 15;
  const bin = ((mac[off] & 0x7f) << 24) | (mac[off + 1] << 16) | (mac[off + 2] << 8) | mac[off + 3];
  return String(bin % 10 ** DIGITS).padStart(DIGITS, '0');
}

const same = (a: string, b: string) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));

/**
 * The step a code matches, within the drift window and after `lastStep` (so a
 * code, once used, cannot be replayed), or null.
 */
export function matchStep(secretB32: string, code: string, lastStep: number | null, now = Date.now()): number | null {
  if (!/^\d{6}$/.test(code)) return null;
  const current = stepOf(now);
  for (let s = current - WINDOW; s <= current + WINDOW; s++) {
    if (lastStep !== null && s <= lastStep) continue;
    if (same(codeAt(secretB32, s), code)) return s;
  }
  return null;
}

/** The link an authenticator app reads from the QR code. */
export function otpauthUrl(secretB32: string, account: string, issuer = 'HostelCare') {
  const label = encodeURIComponent(`${issuer}:${account}`);
  return `otpauth://totp/${label}?secret=${secretB32}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=${DIGITS}&period=${STEP_SECONDS}`;
}

// ── Secret at rest ─────────────────────────────────────────────────────────

const key = () => createHash('sha256').update(env.TOTP_ENCRYPTION_KEY ?? `${env.JWT_REFRESH_SECRET}:totp`).digest();

export function sealSecret(plain: string): string {
  const iv = randomBytes(12);
  const c = createCipheriv('aes-256-gcm', key(), iv);
  const enc = Buffer.concat([c.update(plain, 'utf8'), c.final()]);
  return ['v1', iv.toString('base64'), c.getAuthTag().toString('base64'), enc.toString('base64')].join(':');
}

export function openSecret(sealed: string): string {
  const [v, iv, tag, enc] = sealed.split(':');
  if (v !== 'v1') throw new Error('Unknown secret format');
  const d = createDecipheriv('aes-256-gcm', key(), Buffer.from(iv, 'base64'));
  d.setAuthTag(Buffer.from(tag, 'base64'));
  return Buffer.concat([d.update(Buffer.from(enc, 'base64')), d.final()]).toString('utf8');
}

// ── Recovery codes ─────────────────────────────────────────────────────────

const RC_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';

/** Eight codes like "k7mq-x2pz", each good for one sign-in. */
export function newRecoveryCodes(n = 8): string[] {
  return Array.from({ length: n }, () => {
    const b = randomBytes(8);
    const chars = [...b].map((x) => RC_ALPHABET[x % RC_ALPHABET.length]).join('');
    return `${chars.slice(0, 4)}-${chars.slice(4, 8)}`;
  });
}

export const normaliseRecovery = (code: string) => code.toLowerCase().replace(/[^a-z0-9]/g, '');

export const hashRecovery = (code: string) => createHmac('sha256', `${env.JWT_REFRESH_SECRET}:totp-recovery`).update(normaliseRecovery(code)).digest('hex');
