import { describe, expect, it } from 'vitest';
import { DynamicListReducerInit } from './DynamicListReducer.init';

interface Data {
  position?: number;
  id: number;
}

const dataSet: Data[] = [
  { position: 1, id: 1 },
  { position: 2, id: 2 },
  { position: 5, id: 5 },
  { position: 6, id: 6 },
  { position: 7, id: 7 },
  { position: 8, id: 8 },
  { position: 20, id: 20 },
  { position: 100, id: 100 },
];

describe('Dynamic List Reducer Init', () => {
  it('generates the initial state', () => {
    const result = DynamicListReducerInit({
      initialValue: dataSet,
      positionPropertyName: 'position',
      allowNewData: true,
      maxItemLimit: 10,
    });

    expect(result).toStrictEqual({
      items: dataSet,
      nextPosition: 101,
      canAddItems: true,
      positionPropertyName: 'position',
      maxItemLimit: 10,
      allowNewData: true,
    });
  });

  it('sorts the data when positionPropertyName is defined', () => {
    const data = [
      { position: 5, id: 5 },
      { position: 2, id: 2 },
      { position: 6, id: 6 },
      { position: 1, id: 1 },
    ];

    const result = DynamicListReducerInit({
      initialValue: data,
      positionPropertyName: 'position',
      allowNewData: true,
      maxItemLimit: 10,
    });

    expect(result.items).toEqual([
      { position: 1, id: 1 },
      { position: 2, id: 2 },
      { position: 5, id: 5 },
      { position: 6, id: 6 },
    ]);
  });

  it('calculates the next position', () => {
    expect(
      DynamicListReducerInit({
        initialValue: dataSet,
        positionPropertyName: 'position',
        allowNewData: true,
        maxItemLimit: 10,
      }).nextPosition,
    ).toBe(101);

    expect(
      DynamicListReducerInit({
        initialValue: dataSet.slice(0, dataSet.length - 1),
        positionPropertyName: 'position',
        allowNewData: true,
        maxItemLimit: 10,
      }).nextPosition,
    ).toBe(21);

    expect(
      DynamicListReducerInit({
        initialValue: [],
        positionPropertyName: 'position',
        allowNewData: true,
        maxItemLimit: 10,
      }).nextPosition,
    ).toBe(1);
  });

  it('calculates canAddItems', () => {
    expect(
      DynamicListReducerInit({
        initialValue: dataSet,
        positionPropertyName: 'position',
        allowNewData: true,
        maxItemLimit: 10,
      }).canAddItems,
    ).toBe(true);

    expect(
      DynamicListReducerInit({
        initialValue: dataSet,
        positionPropertyName: 'position',
        allowNewData: true,
        maxItemLimit: 5,
      }).canAddItems,
    ).toBe(false);

    expect(
      DynamicListReducerInit({
        initialValue: dataSet,
        positionPropertyName: 'position',
        allowNewData: false,
        maxItemLimit: 10,
      }).canAddItems,
    ).toBe(false);
  });
});
