import { FormControl, ValidationErrors, ValidatorFn } from '@angular/forms';
import { StockStatusCodeDTO } from '@swagger/oms';

export function validateSsc(statusCodes: StockStatusCodeDTO[] = []): ValidatorFn | null {
  if (statusCodes) {
    return (c: FormControl): ValidationErrors | null => {
      const ssc = c.value;
      const sscText = c?.parent?.get('sscText');
      const code = statusCodes.find((statusCode) => statusCode.code === ssc);
      if (!!code && !!sscText) {
        sscText.setValue(` - ${code.supplierDescription}`, { emitEvent: false });
        return null;
      } else if (!code && !!sscText) {
        sscText.setValue('', { emitEvent: false });
        return { invalid: 'Meldenummer ist ungültig' };
      }
      return null;
    };
  } else {
    return null;
  }
}
