import { validate } from './validate';

const RULES = {
  a: {
    array: {
      constraints: {
        b: { presence: true, type: 'string' },
        c: { presence: true, type: 'number' },
        d: { presence: true, type: 'boolean' },
      },
    },
  },
};
const RULES_WITH_ATTRIBUTES = {
  a: {
    array: {
      attributes: ['b', 'c', 'd'],
      constraints: {
        b: { presence: true, type: 'string' },
        c: { presence: true, type: 'number' },
        d: { presence: true, type: 'boolean' },
      },
    },
  },
};

describe('Validate array items', () => {
  it('with undefined array', function () {
    const data = {
      a: undefined,
    };
    const validation = validate(data, { a: { array: {} } });

    expect(validation).toStrictEqual({ a: ['Array item is undefined'] });
  });

  it('without item constraints', function () {
    const data = {
      a: [
        { b: 'test', c: 1, d: true },
        { b: 'test', c: 1, d: true },
        { b: 'test', c: 1, d: true },
      ],
    };
    const validation = validate(data, { a: { array: {} } });

    expect(validation).toStrictEqual({ a: ['Item constraints not defined'] });
  });

  it('with attributes list', function () {
    const data = {
      a: [
        { b: 'test', c: 1, d: true },
        { b: 'test', c: 1, d: true, e: false },
        { b: 'test', c: 1, d: true },
      ],
    };
    const validation = validate(data, RULES_WITH_ATTRIBUTES);

    expect(validation).toStrictEqual({
      a: [
        {
          errors: {
            // eslint-disable-next-line quote-props
            '1': {
              e: ["Extra attribute 'e'"],
            },
          },
        },
      ],
    });
  });

  it('validate with success', function () {
    const data = {
      a: [
        { b: 'test', c: 1, d: true },
        { b: 'test', c: 1, d: true },
        { b: 'test', c: 1, d: true },
      ],
    };
    const validation = validate(data, RULES);

    expect(validation).toBe(undefined);
  });

  it('validate with errors', function () {
    const data = {
      a: [
        { b: 'test', c: 1, d: true },
        { b: 'test', c: 1, d: true },
        { b: 'test', c: 1, d: 'true' },
      ],
    };
    const validation = validate(data, RULES);

    expect(validation).toStrictEqual({
      a: [
        {
          errors: {
            // eslint-disable-next-line quote-props
            '2': {
              d: ['D must be of type boolean'],
            },
          },
        },
      ],
    });
  });

  it("can't validate if data is not an object", function () {
    const data = 'test';
    const validation = validate(data, RULES);

    expect(validation).toStrictEqual({});
  });
});
