import { AbstractControl } from '@angular/forms';
import { dateRangeStartStopOrderValidator } from './date-range-order.validator';

describe('dateRangeStartStopOrderValidator', () => {
  // Helper function to create a mock AbstractControl with Date values
  const createGroup = (startValue: any, stopValue: any): AbstractControl => {
    return {
      get: (key: string) => {
        if (key === 'start') {
          return { value: startValue } as AbstractControl;
        }
        if (key === 'stop') {
          return { value: stopValue } as AbstractControl;
        }
        return null;
      },
    } as AbstractControl;
  };

  it('should return null if either start or stop value is missing', () => {
    const validator = dateRangeStartStopOrderValidator('start', 'stop');

    // Missing start value
    let group = createGroup(null, new Date(2022, 0, 1)); // 01.01.2022
    expect(validator(group)).toBeNull();

    // Missing stop value
    group = createGroup(new Date(2022, 0, 1), null);
    expect(validator(group)).toBeNull();
  });

  it('should return null if either start or stop is an invalid date', () => {
    const validator = dateRangeStartStopOrderValidator('start', 'stop');

    // Invalid start date
    const invalidDate = new Date('invalid');
    let group = createGroup(invalidDate, new Date(2022, 0, 1));
    expect(validator(group)).toBeNull();

    // Invalid stop date
    group = createGroup(new Date(2022, 0, 1), invalidDate);
    expect(validator(group)).toBeNull();
  });

  it('should return error { startAfterStop: true } when start date is after stop date', () => {
    const validator = dateRangeStartStopOrderValidator('start', 'stop');

    const group = createGroup(new Date(2022, 0, 2), new Date(2022, 0, 1));
    expect(validator(group)).toEqual({ startAfterStop: true });
  });

  it('should return null when start date equals stop date', () => {
    const validator = dateRangeStartStopOrderValidator('start', 'stop');

    const group = createGroup(new Date(2022, 0, 1), new Date(2022, 0, 1));
    expect(validator(group)).toBeNull();
  });

  it('should return null when start date is before stop date', () => {
    const validator = dateRangeStartStopOrderValidator('start', 'stop');

    const group = createGroup(new Date(2022, 0, 1), new Date(2022, 0, 2));
    expect(validator(group)).toBeNull();
  });
});
