/**
 * Roles Query Hooks
 *
 * React Query hooks for fetching and caching role data.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
import { queryKeys } from '../../lib/queryClient';
import type { Role } from '../../types/entities';

interface RoleListParams {
  limit?: number;
  offset?: number;
}

interface RoleListResponse {
  rows: Role[];
  count: number;
}

/**
 * Fetch list of roles
 */
export function useRolesQuery(params?: RoleListParams) {
  const query = params
    ? `?limit=${params.limit || 100}&offset=${params.offset || 0}`
    : '';

  return useQuery({
    queryKey: queryKeys.roles.list(params),
    queryFn: async (): Promise<Role[]> => {
      const response = await axios.get<RoleListResponse>(`roles${query}`);
      return response.data.rows;
    },
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Fetch single role by ID
 */
export function useRoleQuery(roleId: string | undefined) {
  return useQuery({
    queryKey: queryKeys.roles.detail(roleId || ''),
    queryFn: async (): Promise<Role> => {
      const response = await axios.get<Role>(`roles/${roleId}`);
      return response.data;
    },
    enabled: !!roleId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Update role mutation
 */
export function useUpdateRoleMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({
      id,
      data,
    }: {
      id: string;
      data: Partial<Role>;
    }): Promise<Role> => {
      const response = await axios.put<Role>(`roles/${id}`, { id, data });
      return response.data;
    },
    onSuccess: (data, variables) => {
      queryClient.setQueryData(queryKeys.roles.detail(variables.id), data);
      queryClient.invalidateQueries({ queryKey: queryKeys.roles.all });
    },
  });
}

/**
 * Create role mutation
 */
export function useCreateRoleMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (data: Partial<Role>): Promise<Role> => {
      const response = await axios.post<Role>('roles', { data });
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.roles.all });
    },
  });
}

/**
 * Delete role mutation
 */
export function useDeleteRoleMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: string): Promise<void> => {
      await axios.delete(`roles/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.roles.all });
    },
  });
}

export default useRolesQuery;
