/**
 * Session ratings localStorage helper
 * Tracks which sessions have already been rated to prevent repeat prompts
 */

const STORAGE_KEY = 'patherly_rated_sessions'

interface RatedSessionsData {
  [sessionId: string]: {
    ratedAt: string // ISO timestamp
  }
}

/**
 * Check if a session has already been rated
 */
export function hasRatedSession(sessionId: string): boolean {
  try {
    const data = localStorage.getItem(STORAGE_KEY)
    if (!data) return false

    const rated: RatedSessionsData = JSON.parse(data)
    return sessionId in rated
  } catch (error) {
    console.error('Error checking rated sessions:', error)
    return false
  }
}

/**
 * Mark a session as rated
 */
export function markSessionRated(sessionId: string): void {
  try {
    const data = localStorage.getItem(STORAGE_KEY)
    const rated: RatedSessionsData = data ? JSON.parse(data) : {}

    rated[sessionId] = {
      ratedAt: new Date().toISOString()
    }

    localStorage.setItem(STORAGE_KEY, JSON.stringify(rated))
  } catch (error) {
    console.error('Error marking session as rated:', error)
  }
}

/**
 * Clear all rated session tracking (for testing/debugging)
 */
export function clearRatedSessions(): void {
  try {
    localStorage.removeItem(STORAGE_KEY)
  } catch (error) {
    console.error('Error clearing rated sessions:', error)
  }
}

/**
 * Get all rated session IDs
 */
export function getRatedSessions(): string[] {
  try {
    const data = localStorage.getItem(STORAGE_KEY)
    if (!data) return []

    const rated: RatedSessionsData = JSON.parse(data)
    return Object.keys(rated)
  } catch (error) {
    console.error('Error getting rated sessions:', error)
    return []
  }
}
