/**
 * Auth Store (Zustand) – stato autenticazione globale.
 *
 * Persiste access_token e refresh_token in localStorage.
 * L'utente viene memorizzato in memoria per sicurezza.
 */

import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
import { authApi } from '@/api/auth.api'
import type { LoginRequest, UserResponse } from '@/types/api.types'

interface AuthState {
  user: UserResponse | null
  accessToken: string | null
  refreshToken: string | null
  isAuthenticated: boolean
  isLoading: boolean

  // Actions
  login: (credentials: LoginRequest) => Promise<void>
  logout: () => Promise<void>
  loadUser: () => Promise<void>
  setTokens: (access: string, refresh: string) => void
  clearAuth: () => void
}

export const useAuthStore = create<AuthState>()(
  devtools(
    (set, get) => ({
      user: null,
      accessToken: localStorage.getItem('access_token'),
      refreshToken: localStorage.getItem('refresh_token'),
      isAuthenticated: !!localStorage.getItem('access_token'),
      isLoading: false,

      login: async (credentials) => {
        set({ isLoading: true })
        try {
          const tokens = await authApi.login(credentials)
          localStorage.setItem('access_token', tokens.access_token)
          localStorage.setItem('refresh_token', tokens.refresh_token)

          // Carica i dati utente
          const user = await authApi.me()
          set({
            user,
            accessToken: tokens.access_token,
            refreshToken: tokens.refresh_token,
            isAuthenticated: true,
            isLoading: false,
          })
        } catch (error) {
          set({ isLoading: false })
          throw error
        }
      },

      logout: async () => {
        const { refreshToken } = get()
        if (refreshToken) {
          try {
            await authApi.logout(refreshToken)
          } catch {
            // Ignora errori di logout (token già scaduto)
          }
        }
        get().clearAuth()
      },

      loadUser: async () => {
        const token = localStorage.getItem('access_token')
        if (!token) return

        set({ isLoading: true })
        try {
          const user = await authApi.me()
          set({ user, isAuthenticated: true, isLoading: false })
        } catch {
          get().clearAuth()
          set({ isLoading: false })
        }
      },

      setTokens: (access, refresh) => {
        localStorage.setItem('access_token', access)
        localStorage.setItem('refresh_token', refresh)
        set({ accessToken: access, refreshToken: refresh, isAuthenticated: true })
      },

      clearAuth: () => {
        localStorage.removeItem('access_token')
        localStorage.removeItem('refresh_token')
        set({
          user: null,
          accessToken: null,
          refreshToken: null,
          isAuthenticated: false,
        })
      },
    }),
    { name: 'PecFlow/Auth' },
  ),
)

// Selettori tipizzati
export const selectUser = (s: AuthState) => s.user
export const selectIsAdmin = (s: AuthState) =>
  s.user?.role === 'admin' || s.user?.role === 'super_admin'
export const selectIsAuthenticated = (s: AuthState) => s.isAuthenticated
