/**
 * 角色提取（extract）结果本地草稿：用于断线后继续创作，10 天过期
 */
const STORAGE_KEY = 'le_extract_draft'
const TEN_DAYS_MS = 10 * 24 * 60 * 60 * 1000

export interface ExtractDraftPayload {
  savedAt: number
  imageUrl: string
  extractId: string
  characters: any[]
  /** 接口原始响应，便于扩展 */
  raw?: unknown
}

export function saveExtractDraft(
  payload: Omit<ExtractDraftPayload, 'savedAt'> & { savedAt?: number }
): void {
  const data: ExtractDraftPayload = {
    savedAt: payload.savedAt ?? Date.now(),
    imageUrl: payload.imageUrl,
    extractId: payload.extractId ?? '',
    characters: payload.characters ?? [],
    ...(payload.raw !== undefined ? { raw: payload.raw } : {}),
  }
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
  } catch {
    // quota / 隐私模式等忽略
  }
}

/** 未过期返回草稿并校验字段；过期或损坏则删除并返回 null */
export function loadExtractDraft(): ExtractDraftPayload | null {
  const raw = localStorage.getItem(STORAGE_KEY)
  if (!raw) return null
  try {
    const data = JSON.parse(raw) as ExtractDraftPayload
    if (!data.savedAt || Date.now() - data.savedAt > TEN_DAYS_MS) {
      localStorage.removeItem(STORAGE_KEY)
      return null
    }
    if (!data.imageUrl || !Array.isArray(data.characters)) {
      localStorage.removeItem(STORAGE_KEY)
      return null
    }
    return data
  } catch {
    localStorage.removeItem(STORAGE_KEY)
    return null
  }
}

export function clearExtractDraft(): void {
  try {
    localStorage.removeItem(STORAGE_KEY)
  } catch {
    /* ignore */
  }
}
