import { useState, useEffect } from 'react'
import { guardiaApi } from '../api/clients'

interface AuthUser { username: string; display_name: string; role: string }

export function useAuth() {
  const [user, setUser]       = useState<AuthUser | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const token = sessionStorage.getItem('gm_token')
    if (!token) { setLoading(false); return }
    const cached = sessionStorage.getItem('gm_user')
    if (cached) { try { setUser(JSON.parse(cached)); setLoading(false); return } catch {} }
    guardiaApi.get('/api/auth/me')
      .then(r => { setUser(r.data); sessionStorage.setItem('gm_user', JSON.stringify(r.data)) })
      .catch(() => { sessionStorage.removeItem('gm_token'); sessionStorage.removeItem('gm_user') })
      .finally(() => setLoading(false))
  }, [])

  const login = async (username: string, password: string) => {
    // JSON 방식 (ITSM은 JSON 로그인만 지원)
    const r = await guardiaApi.post('/api/auth/login',
      { username, password },
      { headers: { 'Content-Type': 'application/json' } }
    )
    const { access_token } = r.data
    sessionStorage.setItem('gm_token', access_token)
    const me = await guardiaApi.get('/api/auth/me')
    sessionStorage.setItem('gm_user', JSON.stringify(me.data))
    setUser(me.data)
    return me.data
  }

  const logout = () => {
    sessionStorage.removeItem('gm_token')
    sessionStorage.removeItem('gm_user')
    setUser(null)
    window.location.href = '/login'
  }

  return { user, loading, login, logout }
}
