import { beforeEach, describe, expect, it, vi } from 'vitest'

import {
    clearPostImportSourceDraft,
    loadPostImportSourceDraft,
    savePostImportSourceDraft,
} from '@/lib/postImportStorage'

describe ('post import source draft storage', () => {
  beforeEach (() => {
    sessionStorage.clear ()
    vi.restoreAllMocks ()
  })

  it ('round-trips and clears the URL list source draft', () => {
    expect (savePostImportSourceDraft ('https://example.com')).toBe (true)
    expect (loadPostImportSourceDraft ()).toEqual ({
	source: 'https://example.com' })

    clearPostImportSourceDraft ()

    expect (loadPostImportSourceDraft ()).toEqual ({ source: '' })
  })

  it ('ignores malformed stored drafts', () => {
    sessionStorage.setItem ('post-import-source-draft', '{')

    expect (loadPostImportSourceDraft ()).toEqual ({ source: '' })
  })

  it ('reports storage access failures without throwing', () => {
    const onError = vi.fn ()
    vi.spyOn (Storage.prototype, 'setItem').mockImplementation (() => {
      throw new DOMException ('quota')
    })

    expect (savePostImportSourceDraft ('source', onError)).toBe (false)
    expect (onError).toHaveBeenCalledWith ('ブラウザへ保存できませんでした．')
  })
})
