import { createHash, timingSafeEqual } from 'node:crypto';

export const INTEGRATION_MTLS_HEADERS = {
  clientFingerprint: 'x-hgc-client-cert-fingerprint',
  clientSubject: 'x-hgc-client-cert-subject',
} as const;

/** Normalizes nginx, Traefik, or OpenSSL fingerprint formats to lowercase hex without colons. */
export function normalizeCertificateFingerprint(value: string): string {
  return value.replace(/:/g, '').replace(/\s/g, '').toLowerCase();
}

export function fingerprintFromCertificateDer(der: Buffer): string {
  return createHash('sha256').update(der).digest('hex');
}

export function verifyClientCertificateFingerprint(
  provided: string,
  expected: string,
): boolean {
  const normalizedProvided = normalizeCertificateFingerprint(provided);
  const normalizedExpected = normalizeCertificateFingerprint(expected);

  if (normalizedProvided.length !== normalizedExpected.length) {
    return false;
  }

  const providedBuffer = Buffer.from(normalizedProvided, 'utf8');
  const expectedBuffer = Buffer.from(normalizedExpected, 'utf8');

  return timingSafeEqual(providedBuffer, expectedBuffer);
}

export function isIntegrationMtlsEnabled(): boolean {
  return process.env['INTEGRATION_MTLS_ENABLED'] === 'true';
}
