import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { ApiResponse } from "@/types/api-response";
import { adminRolesService } from "./service";
import {
  RoleResponseDto,
  CreateRoleDto,
  UpdateRoleDto,
  RolePermissionResponseDto,
} from "./types";

export const AdminRolesQueryKeys = {
  all: ["admin-roles"] as const,
  list: () => [...AdminRolesQueryKeys.all, "list"] as const,
};

export function useGetAllRoles() {
  const queryKey = AdminRolesQueryKeys.list();

  const { data, ...rest } = useQuery<ApiResponse<RoleResponseDto[]>>({
    queryKey: queryKey,
    queryFn: adminRolesService.getAll,
  });

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

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

  const { data, ...rest } = useMutation<
    ApiResponse<RoleResponseDto>,
    Error,
    CreateRoleDto
  >({
    mutationFn: (roleData) => adminRolesService.create(roleData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminRolesQueryKeys.all });
    },
  });

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

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

  const { data, ...rest } = useMutation<
    ApiResponse<RoleResponseDto>,
    Error,
    { roleId: string; data: UpdateRoleDto }
  >({
    mutationFn: ({ roleId, data }) => adminRolesService.update(roleId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminRolesQueryKeys.all });
    },
  });

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

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

  const { data, ...rest } = useMutation<
    ApiResponse<null>,
    Error,
    { roleId: string }
  >({
    mutationFn: ({ roleId }) => adminRolesService.remove(roleId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminRolesQueryKeys.all });
    },
  });

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

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

  const { data, ...rest } = useMutation<
    ApiResponse<RolePermissionResponseDto>,
    Error,
    { roleId: string; permissionId: string }
  >({
    mutationFn: ({ roleId, permissionId }) =>
      adminRolesService.assignPermission(roleId, permissionId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminRolesQueryKeys.all });
    },
  });

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

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

  const { data, ...rest } = useMutation<
    ApiResponse<null>,
    Error,
    { roleId: string; permissionId: string }
  >({
    mutationFn: ({ roleId, permissionId }) =>
      adminRolesService.removePermission(roleId, permissionId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: AdminRolesQueryKeys.all });
    },
  });

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