'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as api from '../api/platform-staff';
import type { PlatformRole } from '@horux/shared';

export function useStaff() {
  return useQuery({
    queryKey: ['platform-staff'],
    queryFn: api.listStaff,
    staleTime: 60 * 1000,
  });
}

export function useSearchUsers(q: string) {
  return useQuery({
    queryKey: ['platform-staff-search', q],
    queryFn: () => api.searchUsers(q),
    enabled: q.length >= 2,
    staleTime: 30 * 1000,
  });
}

export function useGrantRole() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ userId, role }: { userId: string; role: PlatformRole }) =>
      api.grantRole(userId, role),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['platform-staff'] }),
  });
}

export function useRevokeRole() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ userId, role }: { userId: string; role: PlatformRole }) =>
      api.revokeRole(userId, role),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['platform-staff'] }),
  });
}
