import { useMutation, useQuery } from '@tanstack/react-query';

import api from '../services/api';
import { UserInfo } from './useStorage';

export const useUserDetail = (
  token: string,
  userId: string,
  userInfo: UserInfo,
  setUserInfo: (newInfo: UserInfo) => void,
) => {
  return useQuery(
    ['user-detail', [token, userId]],
    () => api.userManagement.userDetailGet(token, userId),
    {
      enabled: !!token && !!userId,
      onSuccess: data => {
        setUserInfo({
          ...userInfo,
          personId: data?.personId || '',
          personName: data?.personDisplayName || '',
        });
      },
    },
  );
};

export const useLogout = (token: string) => {
  return useQuery(['logout', token], () => api.login.logout(token), {
    enabled: false,
  });
};

export const useUserRoles = (token: string, userId: string) => {
  return useQuery(
    ['user-roles', [token, userId]],
    () => api.userManagement.userRoleAllGet(token, userId),
    {
      enabled: !!token && !!userId,
    },
  );
};

export const useUpdateUserRole = (
  token: string,
  userInfo: UserInfo,
  setUserInfo: (newInfo: UserInfo) => void,
) => {
  return useMutation(
    ['update-user-roles', [token]],
    (roleId: string) => api.userManagement.userRoleUpdate(token, roleId),
    {
      onSuccess: data => {
        if (!data) return;
        setUserInfo({
          ...userInfo,
          unitId: data.idUnit,
          roleId: data.idRole,
        });
      },
    },
  );
};
