import type { StorageErrorHandler } from '@/lib/postImportTypes'

const SOURCE_DRAFT_KEY = 'post-import-source-draft'


const readStorage = (
    key:       string,
    onError?:  StorageErrorHandler,
): string | null => {
  if (typeof window === 'undefined')
    return null

  try
  {
    return sessionStorage.getItem (key)
  }
  catch
  {
    onError?.('保存済みデータを読み込めませんでした．')
    return null
  }
}


const writeStorage = (
    key:       string,
    value:     string,
    onError?:  StorageErrorHandler,
): boolean => {
  if (typeof window === 'undefined')
    return false

  try
  {
    sessionStorage.setItem (key, value)
    return true
  }
  catch
  {
    onError?.('ブラウザへ保存できませんでした．')
    return false
  }
}


const removeStorage = (
    key:       string,
    onError?:  StorageErrorHandler,
) => {
  if (typeof window === 'undefined')
    return

  try
  {
    sessionStorage.removeItem (key)
  }
  catch
  {
    onError?.('保存済みデータを削除できませんでした．')
  }
}


export const loadPostImportSourceDraft = (
    onError?: StorageErrorHandler,
): { source: string } => {
  const raw = readStorage (SOURCE_DRAFT_KEY, onError)
  if (raw == null)
    return { source: '' }

  try
  {
    const value = JSON.parse (raw) as { source?: string }
    return { source: typeof value.source === 'string' ? value.source : '' }
  }
  catch
  {
    return { source: '' }
  }
}


export const savePostImportSourceDraft = (
    source:    string,
    onError?:  StorageErrorHandler,
): boolean =>
    writeStorage (SOURCE_DRAFT_KEY, JSON.stringify ({ source }), onError)


export const clearPostImportSourceDraft = (
    onError?: StorageErrorHandler,
) => {
  removeStorage (SOURCE_DRAFT_KEY, onError)
}
