import {
  getStaleLastPickupStoreIds,
  parseLastFetchTimestamp,
  updateLastPickupInfo
} from '../../services/lastPickupInfo';

describe('last pickup info', () => {
  const now = new Date('2026-08-05T12:00:00.000Z').getTime();

  it('selects visible entries with a missing or stale check timestamp', () => {
    const config = [
      { id: 'missing' },
      { id: 'stale', lastPickupCheckedAt: '2026-07-29T11:59:59.000Z' },
      { id: 'fresh', lastPickupCheckedAt: '2026-07-30T12:00:01.000Z' },
      { id: 'epoch', lastPickupAt: '1970-01-01T00:00:00.000Z', lastPickupCheckedAt: '2026-08-05T12:00:00.000Z' },
      { id: 'hidden', hidden: true }
    ];

    expect(getStaleLastPickupStoreIds(config, now)).toEqual(['missing', 'stale', 'epoch']);
  });

  it('records a successful check independently from the pickup date', () => {
    const entry = { id: '33875', lastPickupAt: '2026-01-01T00:00:00.000Z' };

    expect(updateLastPickupInfo(entry, 1785945600, '2024-05-01T00:00:00.000Z', new Date('2026-08-05T12:00:00.000Z'))).toBe(true);
    expect(entry).toEqual({
      id: '33875',
      lastPickupAt: '2026-08-05T16:00:00.000Z',
      lastPickupCheckedAt: '2026-08-05T12:00:00.000Z',
      memberSinceAt: '2024-05-01T00:00:00.000Z'
    });
  });

  it('treats a zero last-fetch value as no pickup and records the membership date', () => {
    const entry = { id: '69375', lastPickupAt: '1970-01-01T00:00:00.000Z' };

    expect(updateLastPickupInfo(entry, 0, '2025-07-12T00:00:00.000Z', new Date('2026-08-05T12:00:00.000Z'))).toBe(true);
    expect(entry).toEqual({
      id: '69375',
      lastPickupCheckedAt: '2026-08-05T12:00:00.000Z',
      memberSinceAt: '2025-07-12T00:00:00.000Z'
    });
  });

  it('accepts seconds, milliseconds and ISO timestamps from Foodsharing', () => {
    expect(parseLastFetchTimestamp(1785945600)).toBe(1785945600000);
    expect(parseLastFetchTimestamp(1785945600000)).toBe(1785945600000);
    expect(parseLastFetchTimestamp('2026-08-05T00:00:00.000Z')).toBe(1785888000000);
    expect(parseLastFetchTimestamp(0)).toBeNull();
    expect(parseLastFetchTimestamp('0')).toBeNull();
  });
});
