import { describe, expect, it } from 'vitest';
import { freshGameState, loadGame, saveGame, type StorageLike } from '../src/core/save';

const memStorage = (): StorageLike & { data: Map<string, string> } => {
  const data = new Map<string, string>();
  return {
    data,
    getItem: (k) => data.get(k) ?? null,
    setItem: (k, v) => void data.set(k, v),
    removeItem: (k) => void data.delete(k),
  };
};

describe('save', () => {
  it('roundtrips game state', () => {
    const storage = memStorage();
    const state = freshGameState(4207);
    state.nightIndex = 2;
    state.regulars['p9'] = { patronId: 'p9', timesDenied: 2, lastSeenNight: 1, grudge: 0.68 };
    saveGame(state, storage);
    expect(loadGame(0, storage)).toEqual(state);
  });

  it('missing save → fresh state with fallback seed', () => {
    const loaded = loadGame(77, memStorage());
    expect(loaded).toEqual(freshGameState(77));
  });

  it('corrupt JSON → fresh state, no throw', () => {
    const storage = memStorage();
    storage.setItem('not-tonight-save', '{nope');
    expect(loadGame(5, storage)).toEqual(freshGameState(5));
  });

  it('wrong version/shape → fresh state', () => {
    const storage = memStorage();
    storage.setItem('not-tonight-save', JSON.stringify({ v: 99, seed: 'what' }));
    expect(loadGame(6, storage)).toEqual(freshGameState(6));
  });
});
