import { ERROR, ParcelParams } from './interfaces/interface';
import { validateErrores } from './utils/errores';

export const tagTransform = ({
  dataTypeIn,
  dataTypeOut,
  value,
  unit,
}: ParcelParams): string => {
  validateErrores({
    dataTypeIn,
    dataTypeOut,
    value,
    unit,
  });

  if (dataTypeIn === 'etiqueta1d' && dataTypeOut === 'guia') {
    if (value.length === 15 || value.length === 16)
      return value.substring(1, 12);
    return ERROR.etiqueta1d;
  }

  if (dataTypeIn === 'etiqueta2d' && dataTypeOut === 'guia') {
    if (value.length === 32 || value.length === 33)
      return value.substring(18, 29);
    return ERROR.etiqueta2d;
  }

  if (dataTypeIn === 'etiqueta2d' && dataTypeOut === 'etiqueta1d') {
    if (value.length === 32 || value.length === 33)
      return '7' + value.substring(18);
    return ERROR.etiqueta2d;
  }

  if (dataTypeIn === 'guia' && dataTypeOut === 'etiqueta1d' && unit) {
    if (value.length === 11) {
      const unitStr = unit.toString();
      let resultado: string;

      if (unit < 10) {
        resultado = `7${value}${'00' + unitStr}`;
      } else if (unit >= 10 && unit < 100) {
        resultado = `7${value}${'0' + unitStr}`;
      } else {
        resultado = `7${value}${unitStr}`;
      }

      return resultado;
    }
    return ERROR.guia;
  }

  return value.substring(0, 11);
};
