import {
  bulkTouchesSupplier,
  primarySupplierChanged,
  supplierKey,
  supplierListChanged,
} from './md-supplier-guard';

describe('md-supplier-guard', () => {
  describe('supplierKey', () => {
    it('uses the master id, else the typed name (case-insensitive)', () => {
      expect(supplierKey({ supplier_id: 's1', supplier_name_text: 'X' })).toBe('id:s1');
      expect(supplierKey({ supplier_name_text: '  Ali Tours ' })).toBe('name:ali tours');
      expect(supplierKey({ supplier_name_text: '' })).toBeNull();
      expect(supplierKey(null)).toBeNull();
    });
  });

  describe('supplierListChanged', () => {
    it('same suppliers re-sent (cost / vehicle edit) → not a change', () => {
      expect(
        supplierListChanged(
          [{ supplier_id: 'a' }, { supplier_name_text: 'Typed' }],
          [{ supplier_name_text: 'typed' }, { supplier_id: 'a' }],
        ),
      ).toBe(false);
    });

    it('adding, swapping or removing a supplier → change', () => {
      expect(
        supplierListChanged([{ supplier_id: 'a' }], [{ supplier_id: 'a' }, { supplier_id: 'b' }]),
      ).toBe(true);
      expect(supplierListChanged([{ supplier_id: 'a' }], [{ supplier_id: 'b' }])).toBe(true);
      expect(supplierListChanged([{ supplier_id: 'a' }], [])).toBe(true);
      expect(supplierListChanged([], [{ supplier_name_text: 'New' }])).toBe(true);
    });
  });

  describe('primarySupplierChanged', () => {
    const item = { supplier_id: 'a', supplier_name_text: null };
    it('same id → no change; new id, typed name or clear → change', () => {
      expect(primarySupplierChanged(item, { supplier_id: 'a' })).toBe(false);
      expect(primarySupplierChanged(item, { supplier_id: 'b' })).toBe(true);
      expect(primarySupplierChanged(item, { supplier_id: null, supplier_name_text: 'New' })).toBe(
        true,
      );
      expect(primarySupplierChanged(item, { supplier_id: null, supplier_name_text: null })).toBe(
        true,
      );
    });
    it('no supplier fields → no change', () => {
      expect(primarySupplierChanged(item, {})).toBe(false);
    });
  });

  describe('bulkTouchesSupplier', () => {
    it('only when a supplier is set or explicitly cleared', () => {
      expect(bulkTouchesSupplier({})).toBe(false);
      expect(bulkTouchesSupplier({ supplier_id: 's1' })).toBe(true);
      expect(bulkTouchesSupplier({ supplier_name_text: 'New' })).toBe(true);
      expect(bulkTouchesSupplier({ supplier_id: null, supplier_name_text: null })).toBe(true);
    });
  });
});
