import { describe, expect, it } from 'vitest'
import { createSampleData } from './sampleData'
import { parseState, STORAGE_KEY, storageAdapter } from './storage'

describe('versioned storage adapter', () => {
  it('round trips a valid backup', () => {
    const state = createSampleData()
    expect(storageAdapter.import(storageAdapter.export(state))).toEqual(state)
  })

  it('rejects unsupported versions and orphaned tasks', () => {
    expect(() => parseState({ version: 2, goals: [], tasks: [] })).toThrow(/version/i)
    const state = createSampleData()
    expect(() => parseState({ ...state, goals: [] })).toThrow(/does not exist/i)
  })

  it('recovers from corrupt browser data', () => {
    const fakeStorage = { getItem: (key: string) => key === STORAGE_KEY ? '{bad json' : null }
    const result = storageAdapter.load(fakeStorage)
    expect(result.warning).toMatch(/could not be read/i)
    expect(result.state.goals).toHaveLength(4)
  })
})
