import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
import { isAfter, isValid } from 'date-fns';

/**
 * Validator function to check that the start date is not after the stop date.
 *
 * This validator retrieves the values for the start and stop dates from the form group using
 * the provided keys. It performs the following checks:
 * - If either date is missing, the validation passes.
 * - If either date is invalid, the validation passes.
 * - If the start date is after the stop date, a validation error is returned.
 *
 * @param startKey - The key identifying the control containing the start date.
 * @param stopKey - The key identifying the control containing the stop date.
 * @returns A ValidatorFn that returns a ValidationErrors object with {startAfterStop: true}
 *          if the start date is after the stop date, otherwise null.
 */

// TODO: Utils auslagern
export function dateRangeStartStopOrderValidator(
  startKey: string,
  stopKey: string,
): ValidatorFn {
  return (group: AbstractControl): ValidationErrors | null => {
    const start: Date | null = group.get(startKey)?.value ?? null;
    const stop: Date | null = group.get(stopKey)?.value ?? null;

    if (!start || !stop) return null;
    if (!isValid(start) || !isValid(stop)) return null;

    if (isAfter(start, stop)) {
      return { startAfterStop: true };
    }

    return null;
  };
}
