import {
  filterForChatbot,
  filterAllForChatbot,
  packSizeOf,
} from './chatbot-catalog';

const variant = (option: string, enabled = true, product = 'SC 727') => ({
  name: `${product} - ${option}`,
  attributesJson: JSON.stringify([
    { id: 0, name: 'Weight', slug: 'weight', option },
  ]),
  enabled,
});

describe('chatbot catalog rules', () => {
  it('reads the pack size from the Weight attribute or the name suffix', () => {
    expect(packSizeOf(variant('50 000 Kernels'))).toBe('50 000 Kernels');
    expect(packSizeOf({ name: 'SC 727 - 25kg' })).toBe('25kg');
    expect(packSizeOf({ name: 'SC 727' })).toBeNull();
  });

  it('keeps only the 5kg and 2kg SC 727 variants', () => {
    const product = {
      name: 'SC 727',
      variants: [
        '10kg',
        '50 000 Kernels',
        '5kg',
        '25kg',
        '2kg',
        '20 000 Kernels',
        '50 000 Kernels Gaucho Treated',
      ].map((o) => variant(o)),
    };
    expect(
      filterForChatbot(product)!.variants!.map((v) => packSizeOf(v)),
    ).toEqual(['5kg', '2kg']);
  });

  it('hides standalone SC 727 products in removed pack sizes', () => {
    const names = [
      'SC 727 - 10kg',
      'SC 727 - 20 000 Kernels',
      'SC 727 - 25kg',
      'SC 727 - 2kg',
      'SC 727 - 50 000 Kernels',
      'SC 727 - 5kg',
    ];
    const kept = filterAllForChatbot(
      names.map((name) => ({ name, variants: [] })),
    );
    expect(kept.map((p) => p.name)).toEqual(['SC 727 - 2kg', 'SC 727 - 5kg']);
  });

  it('drops variants disabled in the store, and products with none left', () => {
    const partly = {
      name: 'SC 719',
      variants: [
        variant('10kg', false, 'SC 719'),
        variant('25kg', true, 'SC 719'),
      ],
    };
    expect(
      filterForChatbot(partly)!.variants!.map((v) => packSizeOf(v)),
    ).toEqual(['25kg']);

    const allDisabled = {
      name: 'SC 727',
      variants: [variant('5kg', false), variant('2kg', false)],
    };
    expect(filterForChatbot(allDisabled)).toBeNull();
  });

  it('leaves other products untouched', () => {
    const product = {
      name: 'SC 719',
      variants: ['10kg', '25kg'].map((o) => variant(o, true, 'SC 719')),
    };
    expect(filterForChatbot(product)).toBe(product);
  });

  it('hides lay-by listings', () => {
    const layby = {
      name: 'SC 301',
      description: 'Hybrid maize\n\nCategories: Layby, Field Crops',
      variants: [variant('10kg', true, 'SC 301')],
    };
    const regular = {
      name: 'SC 301',
      description:
        'Hybrid maize\n\nCategories: White Maize, Ultra-Early Maturing Varieties',
      variants: [variant('5kg', true, 'SC 301')],
    };
    expect(filterAllForChatbot([layby, regular])).toEqual([regular]);
  });
});
