import { create } from 'zustand'
import { persist } from 'zustand/middleware'

export interface AuthUser {
  id: number
  username: string
  nombre: string
  rol: string
  permisos: string[]
  mustChangePassword: boolean // UDT-008
}

interface SetAuthPayload {
  user: AuthUser
  accessToken: string
  refreshToken: string
  expiresIn: number // seconds from backend
}

interface AuthState {
  user: AuthUser | null
  accessToken: string | null
  refreshToken: string | null
  expiresAt: number | null // ms epoch UTC
  setAuth: (payload: SetAuthPayload) => void
  updateUser: (patch: Partial<AuthUser>) => void // UDT-008
  updateAccess: (accessToken: string, refreshToken: string, expiresAt: number) => void
  clearAuth: () => void
  logout: () => Promise<void>
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      accessToken: null,
      refreshToken: null,
      expiresAt: null,

      setAuth: (payload) =>
        set({
          user: payload.user,
          accessToken: payload.accessToken,
          refreshToken: payload.refreshToken,
          expiresAt: Date.now() + payload.expiresIn * 1000,
        }),

      updateUser: (patch) =>
        set((s) => ({
          user: s.user ? { ...s.user, ...patch } : null,
        })),

      updateAccess: (accessToken, refreshToken, expiresAt) =>
        set({ accessToken, refreshToken, expiresAt }),

      clearAuth: () =>
        set({
          user: null,
          accessToken: null,
          refreshToken: null,
          expiresAt: null,
        }),

      logout: async () => {
        const { accessToken, clearAuth } = get()
        if (accessToken) {
          try {
            // Lazy import to break circular dependency with axiosClient
            const { logout: apiLogout } = await import('@/features/auth/api/authApi')
            await apiLogout()
          } catch {
            // Ignore API errors — local logout is always safe
          }
        }
        clearAuth()
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        user: state.user,
        accessToken: state.accessToken,
        refreshToken: state.refreshToken,
        expiresAt: state.expiresAt,
      }),
    },
  ),
)
