import { FormControl } from '@angular/forms';

import { arrayMinLengthValidator } from './array-min-length.validator';

describe('arrayMinLengthValidator', () => {
  describe('when value is null or undefined', () => {
    it('should reject null', () => {
      const control = new FormControl(null, arrayMinLengthValidator(1));
      expect(control.errors).toEqual({
        arrayMinLength: { requiredLength: 1, actualLength: 0 },
      });
    });

    it('should reject undefined', () => {
      const control = new FormControl(undefined, arrayMinLengthValidator(1));
      expect(control.errors).toEqual({
        arrayMinLength: { requiredLength: 1, actualLength: 0 },
      });
    });
  });

  describe('when value is not an array', () => {
    it('should reject a string', () => {
      const control = new FormControl('not-an-array', arrayMinLengthValidator(1));
      expect(control.errors).toEqual({
        arrayMinLength: { requiredLength: 1, actualLength: 0 },
      });
    });

    it('should reject a number', () => {
      const control = new FormControl(42, arrayMinLengthValidator(1));
      expect(control.errors).toEqual({
        arrayMinLength: { requiredLength: 1, actualLength: 0 },
      });
    });

    it('should reject an object', () => {
      const control = new FormControl({ length: 5 }, arrayMinLengthValidator(1));
      expect(control.errors).toEqual({
        arrayMinLength: { requiredLength: 1, actualLength: 0 },
      });
    });
  });

  describe('when value is an array', () => {
    it('should reject an empty array when min is 1', () => {
      const control = new FormControl([], arrayMinLengthValidator(1));
      expect(control.errors).toEqual({
        arrayMinLength: { requiredLength: 1, actualLength: 0 },
      });
    });

    it('should reject an array shorter than min', () => {
      const control = new FormControl(['a'], arrayMinLengthValidator(2));
      expect(control.errors).toEqual({
        arrayMinLength: { requiredLength: 2, actualLength: 1 },
      });
    });

    it('should accept an array of exactly min length', () => {
      const control = new FormControl(['a'], arrayMinLengthValidator(1));
      expect(control.errors).toBeNull();
    });

    it('should accept an array longer than min', () => {
      const control = new FormControl(['a', 'b', 'c'], arrayMinLengthValidator(1));
      expect(control.errors).toBeNull();
    });

    it('should accept any non-empty array when min is 0', () => {
      const control = new FormControl([], arrayMinLengthValidator(0));
      expect(control.errors).toBeNull();
    });
  });
});
