import { openJson, sealJson } from './medicalCrypto';
import { getTenantIdOrThrow } from './tenantContext';

/**
 * Government ID numbers at rest for Enterprise tenants (6 Nov 2026): a staff
 * member's PAN, Aadhaar, UAN, PF and ESIC numbers and an employee's KYC ID number
 * are sealed like medical records, with the same key, and bound to the tenant, so a database copy reads
 * as noise and a value moved to another tenant will not open.
 *
 * Every reader goes through `openIdNumber`, which hands back anything not sealed
 * as it is: other tenant kinds store plain values and keep doing so.
 */
const SEALED = /^m[12]:[^:]+:[^:]+:[^:]+$/;
const contextOf = (tenantId: string) => `id-number:${tenantId}`;

export const isSealedIdNumber = (value: string) => SEALED.test(value);

/** Seal a number for the tenant in context, or an explicit one (for the backfill script). */
export function sealIdNumber(value: string, tenantId = getTenantIdOrThrow()): string {
  return isSealedIdNumber(value) ? value : sealJson(value, contextOf(tenantId));
}

/**
 * The number as entered. A value that will not open (a key was replaced without
 * re-sealing) reads as absent and is logged, so one bad row cannot take a whole
 * list down.
 */
export function openIdNumber(stored: string | null | undefined, tenantId?: string): string | null {
  if (!stored) return null;
  if (!isSealedIdNumber(stored)) return stored;
  try {
    return openJson<string>(stored, contextOf(tenantId ?? getTenantIdOrThrow()));
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error('[id-number] could not open a sealed value:', (err as Error).message);
    return null;
  }
}
