import { create } from 'zustand'
import type { UserProfile } from '../types'

// OWASP JWT Cheat Sheet — Token Storage on Client Side:
// sessionStorage is used (NOT localStorage) because it is cleared when the browser
// tab is closed, reducing the window during which a stolen token is useful.
// The companion __Secure-Fgp cookie is HttpOnly, so JavaScript (including an XSS
// payload) cannot read it — a stolen token alone is not enough to impersonate.
interface AuthState {
  token: string | null
  user: UserProfile | null
  setAuth: (token: string, user: UserProfile) => void
  logout: () => void
}

export const useAuthStore = create<AuthState>((set) => ({
  token: sessionStorage.getItem('token'),
  user: (() => {
    const u = sessionStorage.getItem('user')
    return u ? JSON.parse(u) : null
  })(),
  setAuth: (token, user) => {
    sessionStorage.setItem('token', token)
    sessionStorage.setItem('user', JSON.stringify(user))
    set({ token, user })
  },
  logout: () => {
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('user')
    set({ token: null, user: null })
  },
}))
