// In-memory TTL cache for `ProtocolAdapter.lookupAccount` results.
//
// Mastodon's `/api/v2/search?resolve=true` triggers webfinger + ActivityPub
// inbox discovery on the home instance. Mastodon.social rate-limits this at
// ~5/min per token; other servers vary. Cache results so a remote handle
// tapped multiple times in the same minute (a profile re-render, two posts
// from the same author, the "Search for X" recovery affordance bouncing
// back to the profile screen) doesn't burn the rate-limit budget.
//
// The cache is per-process (cleared on app restart) and keyed on
// `(protocol, normalised handle)`. The active account flips clear the
// cache to avoid the (admittedly low-likelihood) case where one account's
// home server resolved a handle to a different `Account.id` than another
// account would. The cache also rotates on TTL expiry.

import { AccountStore } from 'src/state/accountStore'
import type { AccountLookupResult } from './types'

const TTL_MS = 60 * 60 * 1000 // 1 hour

type CacheEntry = {
  expiresAt: number
  value: AccountLookupResult
}

let cacheForAccountId: string | null = null
const entries = new Map<string, CacheEntry>()

function reset(activeId: string | null) {
  cacheForAccountId = activeId
  entries.clear()
}

function ensureScope() {
  const activeId = AccountStore.activeId()
  if (activeId !== cacheForAccountId) reset(activeId)
}

export const lookupCache = {
  get(key: string): AccountLookupResult | undefined {
    ensureScope()
    const hit = entries.get(key)
    if (!hit) return undefined
    if (hit.expiresAt < Date.now()) {
      entries.delete(key)
      return undefined
    }
    return hit.value
  },

  set(key: string, value: AccountLookupResult): void {
    ensureScope()
    // Don't cache `rejected` outcomes — those are typically network/auth
    // failures that the user can retry past, not stable miss states.
    if (value.kind === 'rejected') return
    entries.set(key, { value, expiresAt: Date.now() + TTL_MS })
  },

  clear(): void {
    entries.clear()
  },
}
