import { describe, it, expect } from 'vitest';
import { SaveManager, type StorageLike } from '../SaveManager';

function memoryStorage(): StorageLike {
    const map = new Map<string, string>();
    return {
        getItem: (k) => map.get(k) ?? null,
        setItem: (k, v) => void map.set(k, v),
        removeItem: (k) => void map.delete(k),
        key: (i) => [...map.keys()][i] ?? null,
        get length() {
            return map.size;
        }
    };
}

describe('SaveManager', () => {
    it('сохраняет и загружает по слотам', () => {
        const sm = new SaveManager(memoryStorage());
        sm.save('slot1', { x: 3, y: 4 });
        expect(sm.load<{ x: number; y: number }>('slot1')).toEqual({ x: 3, y: 4 });
        expect(sm.load('unknown')).toBeNull();
    });

    it('битый JSON -> null', () => {
        const storage = memoryStorage();
        storage.setItem('save:broken', '{oops');
        const sm = new SaveManager(storage);
        expect(sm.load('broken')).toBeNull();
    });

    it('listSlots и delete', () => {
        const sm = new SaveManager(memoryStorage());
        sm.save('a', 1);
        sm.save('b', 2);
        expect(sm.listSlots().sort()).toEqual(['a', 'b']);
        sm.delete('a');
        expect(sm.listSlots()).toEqual(['b']);
    });
});