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

/**
 * Sealing medical records (Sprint 6, TEPL): AES-256-GCM with a key of their
 * own, so a database copy reads as noise and a TOTP key leak does not open
 * them. Each value carries its version, IV and tag.
 *
 * Sprint 7 hardening: "m2" values are bound to whose record they are (the
 * context — tenant and employee — is the GCM additional data), so a sealed
 * value copied onto another row will not open; the tag must be the full 16
 * bytes. "m1" values from before still open.
 */
const key = () => createHash('sha256').update(env.MEDICAL_ENCRYPTION_KEY ?? `${env.JWT_REFRESH_SECRET}:medical-records`).digest();
const TAG = 16;

/** What a sealed value is bound to: the tenant and the employee it belongs to. */
export const medicalContext = (tenantId: string, studentProfileId: string) => `${tenantId}:${studentProfileId}`;

export function sealJson(value: unknown, context?: string): string {
  const iv = randomBytes(12);
  const c = createCipheriv('aes-256-gcm', key(), iv, { authTagLength: TAG });
  if (context) c.setAAD(Buffer.from(context, 'utf8'));
  const enc = Buffer.concat([c.update(JSON.stringify(value), 'utf8'), c.final()]);
  return [context ? 'm2' : 'm1', iv.toString('base64'), c.getAuthTag().toString('base64'), enc.toString('base64')].join(':');
}

export function openJson<T>(sealed: string, context?: string): T {
  const [v, iv, tag, enc] = sealed.split(':');
  if (v !== 'm1' && v !== 'm2') throw new Error('Unknown sealed format');
  if (v === 'm2' && !context) throw new Error('This value is bound to a record');
  const t = Buffer.from(tag ?? '', 'base64');
  if (t.length !== TAG) throw new Error('The seal is damaged');
  const d = createDecipheriv('aes-256-gcm', key(), Buffer.from(iv, 'base64'), { authTagLength: TAG });
  if (v === 'm2') d.setAAD(Buffer.from(context!, 'utf8'));
  d.setAuthTag(t);
  return JSON.parse(Buffer.concat([d.update(Buffer.from(enc, 'base64')), d.final()]).toString('utf8')) as T;
}
