'use server';

import type { IMedipostResponseXMLBase } from '@/packages/shared/src/types/medipost-analysis';

import { parseXML } from '../util/xml.service';
import { MedipostValidationError } from './MedipostValidationError';

export async function validateMedipostResponse(
  response: string,
  { canHaveEmptyCode = false }: { canHaveEmptyCode?: boolean } = {},
) {
  const parsed: IMedipostResponseXMLBase = await parseXML(response);
  const code = parsed.ANSWER?.CODE;
  if (canHaveEmptyCode) {
    if (code && code !== 0) {
      console.error('Bad response', response);
      throw new MedipostValidationError(response);
    }
    return;
  }

  if (typeof code !== 'number' || (code !== 0 && !canHaveEmptyCode)) {
    console.error('Bad response', response);
    throw new MedipostValidationError(response);
  }
}
