const { z } = require('zod');

const resultSchema = z.object({
  test_code: z.string().min(1),
  value: z.union([z.string(), z.number()]),
  unit: z.string().optional(),
  flag: z.string().optional(),
  meta: z.record(z.string(), z.any()).optional()
});

const canonicalSchema = z.object({
  instrument_id: z.string().min(1),
  sample_id: z.string().min(1),
  result_time: z
    .string()
    .refine((value) => !Number.isNaN(Date.parse(value)), 'invalid ISO timestamp'),
  results: z.array(resultSchema).min(1),
  unit: z.string().optional(),
  flag: z.string().optional(),
  patient_id: z.string().optional(),
  operator_id: z.string().optional(),
  meta: z.record(z.string(), z.any()).optional()
});

function normalize(payload) {
  try {
    return canonicalSchema.parse(payload);
  } catch (error) {
    console.error('normalization failed', error);
    throw error;
  }
}

module.exports = {
  normalize,
  schema: canonicalSchema
};
