jest.mock('../../services/foodsharingClient', () => ({
  fetchConversations: jest.fn()
}));

jest.mock('socket.io-client', () => ({
  io: jest.fn()
}));

jest.mock('../../services/requestLogStore', () => ({
  add: jest.fn()
}));

jest.mock('../../services/sessionStore', () => ({
  get: jest.fn()
}));

const {
  collectStoreIds,
  extractStoreIdFromHref,
  getMatchingActiveEntries,
  getMessageWatcherSettings,
  isPotentialMessageSocketEvent
} = require('../../services/storeMessageWatcher');

describe('storeMessageWatcher', () => {
  test('extracts store ids from modern and legacy foodsharing links', () => {
    expect(extractStoreIdFromHref('/store/33875')).toBe('33875');
    expect(extractStoreIdFromHref('/?page=fsbetrieb&id=44975')).toBe('44975');
    expect(extractStoreIdFromHref('/fairteiler/2974')).toBeNull();
  });

  test('detects relevant socket event names', () => {
    expect(isPotentialMessageSocketEvent('conversation:message')).toBe(true);
    expect(isPotentialMessageSocketEvent('notification')).toBe(true);
    expect(isPotentialMessageSocketEvent('connect')).toBe(false);
  });

  test('matches only active entries for the affected store', () => {
    const config = [
      { id: '33875', active: true },
      { id: 33875, active: false },
      { id: '44975', active: true }
    ];

    expect(getMatchingActiveEntries(config, '33875')).toEqual([{ id: '33875', active: true }]);
  });

  test('collects store ids from socket-like payloads', () => {
    const ids = Array.from(
      collectStoreIds([
        { conversation: { storeId: 44975 } },
        { href: '/store/33875' },
        { text: '/?page=fsbetrieb&id=42264' }
      ])
    ).sort();

    expect(ids).toEqual(['33875', '42264', '44975']);
  });

  test('normalizes message watcher settings', () => {
    expect(getMessageWatcherSettings({ messageWatcherFallbackCron: '*/15 * * * *' })).toMatchObject({
      socketEnabled: true,
      fallbackEnabled: true,
      fallbackCron: '*/15 * * * *',
      debugLogging: true
    });
    expect(
      getMessageWatcherSettings({
        messageWatcherSocketEnabled: false,
        messageWatcherFallbackEnabled: false,
        messageWatcherFallbackCron: 'invalid',
        messageWatcherDebugLogging: false
      })
    ).toMatchObject({
      socketEnabled: false,
      fallbackEnabled: false,
      fallbackCron: '0 6-23 * * *',
      debugLogging: false
    });
  });
});
