import type { ChatMessage } from './protocol'

const STORAGE_PREFIX = 'chat:'
const MAX_MESSAGES_PER_SESSION = 500

function storageKey(sessionId: string): string {
  return `${STORAGE_PREFIX}${sessionId}`
}

/** Load messages for a session from localStorage */
export function loadMessages(sessionId: string): ChatMessage[] {
  try {
    const raw = localStorage.getItem(storageKey(sessionId))
    if (!raw) return []
    const parsed = JSON.parse(raw) as unknown
    if (!Array.isArray(parsed)) return []
    return parsed as ChatMessage[]
  } catch {
    return []
  }
}

/** Save messages for a session to localStorage (keeps latest N) */
export function saveMessages(sessionId: string, messages: ChatMessage[]): void {
  try {
    const trimmed =
      messages.length > MAX_MESSAGES_PER_SESSION
        ? messages.slice(-MAX_MESSAGES_PER_SESSION)
        : messages
    localStorage.setItem(storageKey(sessionId), JSON.stringify(trimmed))
  } catch {
    // Storage full — remove oldest session caches and retry once
    try {
      evictOldest()
      const trimmed =
        messages.length > MAX_MESSAGES_PER_SESSION
          ? messages.slice(-MAX_MESSAGES_PER_SESSION)
          : messages
      localStorage.setItem(storageKey(sessionId), JSON.stringify(trimmed))
    } catch {
      // Still failing, silently ignore
    }
  }
}

/** Remove all stored messages for a session */
export function clearMessages(sessionId: string): void {
  try {
    localStorage.removeItem(storageKey(sessionId))
  } catch {
    // ignore
  }
}

/** Evict the oldest chat session cache to free space */
function evictOldest(): void {
  let oldestKey: string | null = null
  let oldestTimestamp = Infinity

  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i)
    if (!key?.startsWith(STORAGE_PREFIX)) continue
    try {
      const raw = localStorage.getItem(key)
      if (!raw) continue
      const msgs = JSON.parse(raw) as ChatMessage[]
      const firstTs = msgs[0]?.timestamp ?? Infinity
      if (firstTs < oldestTimestamp) {
        oldestTimestamp = firstTs
        oldestKey = key
      }
    } catch {
      // Corrupt entry — remove it
      if (key) localStorage.removeItem(key)
      return
    }
  }

  if (oldestKey) {
    localStorage.removeItem(oldestKey)
  }
}
