import { formatDate } from '@msfa-utils/format-to-date.util';
import { parseISO } from 'date-fns';
import { extractAvropPeriods } from './extract-avrop-periods';

describe('extract-avrop-periods', function () {
  describe('when avrop is between 2021-05-01 and 2021-08-15', function () {
    const startDate = parseISO('2021-05-01');
    const endDate = parseISO('2021-08-15');
    const periods = extractAvropPeriods(startDate, endDate);

    it('should yield 3 periods between 2021-05-01 and 2021-08-15', function () {
      expect(periods.map(period => period.periodId)).toEqual(['2021-05', '2021-06', '2021-07', '2021-08']);
    });

    it('first period should start at startDate', function () {
      expect(periods[0].startDate).toEqual(startDate);
    });

    it('second period should start with first day of month', function () {
      expect(formatDate(periods[1].startDate)).toEqual('2021-06-01');
    });

    it('second period should end with last day of month', function () {
      expect(formatDate(periods[1].endDate)).toEqual('2021-06-30');
    });

    it('last period should end with last day of avrop', function () {
      expect(formatDate(periods[periods.length - 1].endDate)).toEqual('2021-08-15');
    });
  });

  it('should throw if startDate is greater than endDate', function () {
    const startDate = parseISO('2021-09-01');
    const endDate = parseISO('2021-08-15');
    expect(() => extractAvropPeriods(startDate, endDate)).toThrowError();
  });

  it('should throw if startDate is null', function () {
    const startDate = null;
    const endDate = parseISO('2021-08-15');
    expect(() => extractAvropPeriods(startDate, endDate)).toThrowError();
  });

  it('should throw if endDate is null', function () {
    const startDate = parseISO('2021-08-15');
    const endDate = null;
    expect(() => extractAvropPeriods(startDate, endDate)).toThrowError();
  });

  it('should work if startDate is end of short month', function () {
    const startDate = parseISO('2021-02-28');
    const endDate = parseISO('2021-03-31');
    const periods = extractAvropPeriods(startDate, endDate);
    expect(periods.map(period => period.periodId)).toEqual(['2021-02', '2021-03']);
  });
});
