import { Injectable } from '@angular/core';
import { UntypedFormGroup } from '@angular/forms';
import { ErrorFormatterHelper } from '@shared/ui-api/helpers/error-formatter-helper';

@Injectable({
  providedIn: 'root'
})
export class FormErrorsHelper {

  public static setValidationErrors(formGroup: UntypedFormGroup, prefix: string, validationErrors: Record<string, any>) {
    for (const controlName of Object.keys(formGroup.controls)) {
      const control = formGroup.controls[controlName];
      const errorName = prefix ? `${prefix}.${controlName}` : controlName;
      if (!control.valid) {
        if (control instanceof UntypedFormGroup) {
          this.setValidationErrors(control, errorName, validationErrors);
        } else {
          if (control.errors) {
            validationErrors[errorName] = ErrorFormatterHelper.formatError(
              control.errors, control.errors?.min?.min, control.errors?.max?.max
            );
          }
        }
      }
    }
    return validationErrors;
  }
}
