export type DraftWindowSnapshot = {
  title: string
  slug: string
  path: string
  markdown: string
  savedMarkdown: string
  createdAt: number
}

const STORAGE_PREFIX = 'termi-admin-post-draft:'
const POLISH_RESULT_PREFIX = 'termi-admin-post-polish-result:'

export type PolishWindowResult = {
  draftKey: string
  markdown: string
  target: 'editor' | 'create'
  createdAt: number
}

export function saveDraftWindowSnapshot(snapshot: Omit<DraftWindowSnapshot, 'createdAt'>) {
  const key = `${STORAGE_PREFIX}${snapshot.slug}:${Date.now()}`
  const payload: DraftWindowSnapshot = {
    ...snapshot,
    createdAt: Date.now(),
  }

  window.localStorage.setItem(key, JSON.stringify(payload))
  return key
}

export function loadDraftWindowSnapshot(key: string | null) {
  if (!key) {
    return null
  }

  const raw = window.localStorage.getItem(key)
  if (!raw) {
    return null
  }

  try {
    return JSON.parse(raw) as DraftWindowSnapshot
  } catch {
    return null
  }
}

export function savePolishWindowResult(
  draftKey: string,
  markdown: string,
  target: 'editor' | 'create',
) {
  const payload: PolishWindowResult = {
    draftKey,
    markdown,
    target,
    createdAt: Date.now(),
  }

  window.localStorage.setItem(`${POLISH_RESULT_PREFIX}${draftKey}`, JSON.stringify(payload))
  return payload
}

function parsePolishWindowResult(raw: string | null) {
  if (!raw) {
    return null
  }

  try {
    return JSON.parse(raw) as PolishWindowResult
  } catch {
    return null
  }
}

export function readPolishWindowResult(key: string | null) {
  if (!key) {
    return null
  }

  const storageKey = `${POLISH_RESULT_PREFIX}${key}`
  return parsePolishWindowResult(window.localStorage.getItem(storageKey))
}

export function consumePolishWindowResult(key: string | null) {
  if (!key) {
    return null
  }

  const storageKey = `${POLISH_RESULT_PREFIX}${key}`
  const parsed = parsePolishWindowResult(window.localStorage.getItem(storageKey))
  if (!parsed) {
    return null
  }

  window.localStorage.removeItem(storageKey)
  return parsed
}
