import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { ApiResponse } from "@/types/api-response";
import { adminUsersService } from "./service";
import {
  UserRoleResponseDto,
  UsersQueryParams,
  PaginatedUsersResponse,
} from "./types";
import { UserResponseDto } from "@/types/user";

export const AdminUsersQueryKeys = {
  all: ["admin-users"] as const,
  list: (params?: UsersQueryParams) =>
    [...AdminUsersQueryKeys.all, "list", params] as const,
};

export function useGetAllUsers(params?: UsersQueryParams) {
  const queryKey = AdminUsersQueryKeys.list(params);

  const { data, ...rest } = useQuery<ApiResponse<PaginatedUsersResponse>>({
    queryKey: queryKey,
    queryFn: () => adminUsersService.getAll(params),
  });

  return { data: data?.data, ...rest };
}

export function useToggleUserActive() {
  const queryClient = useQueryClient();

  const { data, ...rest } = useMutation<
    ApiResponse<UserResponseDto>,
    Error,
    { userId: string }
  >({
    mutationFn: ({ userId }) => adminUsersService.toggleActive(userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminUsersQueryKeys.all });
    },
  });

  return { data: data?.data, ...rest };
}

export function useAssignRole() {
  const queryClient = useQueryClient();

  const { data, ...rest } = useMutation<
    ApiResponse<UserRoleResponseDto>,
    Error,
    { userId: string; roleId: string }
  >({
    mutationFn: ({ userId, roleId }) =>
      adminUsersService.assignRole(userId, roleId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminUsersQueryKeys.all });
    },
  });

  return { data: data?.data, ...rest };
}

export function useRemoveRole() {
  const queryClient = useQueryClient();

  const { data, ...rest } = useMutation<
    ApiResponse<null>,
    Error,
    { userId: string; roleId: string }
  >({
    mutationFn: ({ userId, roleId }) =>
      adminUsersService.removeRole(userId, roleId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminUsersQueryKeys.all });
    },
  });

  return { data: data?.data, ...rest };
}
