type DownloadGatePayload = {
  key: string
  paidAt: string
  amountCny: number
  method: 'wechat' | 'alipay'
}

const STORAGE_PREFIX = 'downloadGate:'

export function hasDownloadAccess(key: string): boolean {
  try {
    const raw = localStorage.getItem(`${STORAGE_PREFIX}${key}`)
    if (!raw) return false
    const parsed = JSON.parse(raw) as DownloadGatePayload
    return parsed?.key === key && parsed.amountCny >= 1
  } catch {
    return false
  }
}

export function grantDownloadAccess(key: string, method: DownloadGatePayload['method']): void {
  const payload: DownloadGatePayload = {
    key,
    paidAt: new Date().toISOString(),
    amountCny: 1,
    method,
  }

  try {
    localStorage.setItem(`${STORAGE_PREFIX}${key}`, JSON.stringify(payload))
  } catch {
    // ignore
  }
}

export function revokeDownloadAccess(key: string): void {
  try {
    localStorage.removeItem(`${STORAGE_PREFIX}${key}`)
  } catch {
    // ignore
  }
}
