import type { Student } from "../types"

const STUDENT_STORAGE_KEY = "student_info"

/**
 * Store student information in localStorage
 * @param student Student object to store
 */
export const setStudent = (student: Student): void => {
  try {
    localStorage.setItem(STUDENT_STORAGE_KEY, JSON.stringify(student))
    console.log("[storage] Student info stored:", { id: student.id, name: student.name })
  } catch (error) {
    console.error("[storage] Failed to store student info:", error)
  }
}

/**
 * Retrieve student information from localStorage
 * @returns Student object or null if not found
 */
export const getStudent = (): Student | null => {
  try {
    const storedStudent = localStorage.getItem(STUDENT_STORAGE_KEY)
    if (storedStudent) {
      const student = JSON.parse(storedStudent) as Student
      console.log("[storage] Student info retrieved:", { id: student.id, name: student.name })
      return student
    }
    console.log("[storage] No student info found in localStorage")
    return null
  } catch (error) {
    console.error("[storage] Failed to retrieve student info:", error)
    return null
  }
}

/**
 * Clear student information from localStorage
 */
export const clearStudent = (): void => {
  try {
    localStorage.removeItem(STUDENT_STORAGE_KEY)
    console.log("[storage] Student info cleared from localStorage")
  } catch (error) {
    console.error("[storage] Failed to clear student info:", error)
  }
}

/**
 * Check if student information exists in localStorage
 * @returns boolean indicating if student info exists
 */
export const hasStudent = (): boolean => {
  try {
    return localStorage.getItem(STUDENT_STORAGE_KEY) !== null
  } catch (error) {
    console.error("[storage] Failed to check student info:", error)
    return false
  }
}
