const mockStorageData = new Map<string, any>();
jest.mock('../storage', () => ({
    __esModule: true,
    default: () => ({
        hasData: async (key: string) => mockStorageData.has(key),
        getData: async <T>(key: string) => mockStorageData.get(key) as T,
        setData: async <T>(key: string, val: T) => void mockStorageData.set(key, val),
    }),
    storageReady: Promise.resolve(),
}));

import { addChoice, getData } from '../service';
import { LunchChoice, MealSlot } from '../../../types/gen/types.gen';

const TODAY = new Date('2025-01-10');
const TODAY_STR = '2025-01-10';
const TODAY_EXTRA_STR = '2025-01-10_extra';

describe('MealSlot storage isolation', () => {
    beforeEach(() => {
        mockStorageData.clear();
        jest.useFakeTimers();
        jest.setSystemTime(TODAY);
    });

    afterEach(() => {
        jest.useRealTimers();
    });

    test('addChoice slot=extra writes only to _extra key, not to obed key, and returns slot=EXTRA', async () => {
        const result = await addChoice('user1', false, LunchChoice.OBJEDNAVAM, undefined, TODAY, MealSlot.EXTRA);
        expect(result.slot).toBe(MealSlot.EXTRA);
        expect(mockStorageData.has(TODAY_EXTRA_STR)).toBe(true);
        expect(mockStorageData.has(TODAY_STR)).toBe(false);
        const extraData = mockStorageData.get(TODAY_EXTRA_STR);
        expect(extraData.choices.OBJEDNAVAM?.['user1']).toBeDefined();
    });

    test('getData slot=extra returns slot===MealSlot.EXTRA and no menus', async () => {
        await addChoice('user1', false, LunchChoice.OBJEDNAVAM, undefined, TODAY, MealSlot.EXTRA);
        const result = await getData(TODAY, MealSlot.EXTRA);
        expect(result.slot).toBe(MealSlot.EXTRA);
        expect(result.menus).toBeUndefined();
    });

    test('addChoice slot=extra does not modify obed data even when obed has PIZZA choice', async () => {
        mockStorageData.set(TODAY_STR, {
            choices: { PIZZA: { user1: { selectedFoods: [0], trusted: false } } },
            todayDayIndex: 4,
            date: '10. 1. 2025',
            isWeekend: false,
            dayIndex: 4,
        });

        await addChoice('user1', false, LunchChoice.OBJEDNAVAM, undefined, TODAY, MealSlot.EXTRA);

        const obed = mockStorageData.get(TODAY_STR);
        expect(obed.choices.PIZZA?.['user1']).toBeDefined();
    });
});
