import { useMutation } from '@tanstack/react-query'
import { login } from '../api/authApi'
import { useAuthStore } from '../../../stores/authStore'

interface LoginVars {
  username: string
  password: string
}

export function useLogin() {
  const setAuth = useAuthStore((s) => s.setAuth)

  return useMutation({
    mutationFn: ({ username, password }: LoginVars) => login(username, password),
    onSuccess: (data) => {
      setAuth({
        user: {
          id: data.usuario.id,
          username: data.usuario.username,
          nombre: data.usuario.nombre,
          rol: data.usuario.rol,
          permisos: data.usuario.permisos ?? [],
          mustChangePassword: data.usuario.mustChangePassword ?? false, // UDT-008
        },
        accessToken: data.accessToken,
        refreshToken: data.refreshToken,
        expiresIn: data.expiresIn,
      })
    },
  })
}
