/**
 * Role and permission hooks.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiGet, apiPost, apiPatch, apiDelete } from './client';

export interface Role {
  id: string;
  name: string;
  permissions: Record<string, any>;
  field_permissions?: Record<string, any>;
}

export interface PermissionItem {
  key: string;
  label: string;
  category: string;
  plugin_name?: string;
}

export interface FieldDefinition {
  module: string;
  field: string;
  label: string;
  sensitivity: string;
}

export interface PermissionsResponse {
  system: PermissionItem[];
  plugins: PermissionItem[];
  all: PermissionItem[];
  field_definitions?: FieldDefinition[];
}

export function useRoles() {
  return useQuery({
    queryKey: ['roles'],
    queryFn: async () => {
      const data = await apiGet<any>('/roles');
      return data;
    },
  });
}

export function usePermissions() {
  return useQuery({
    queryKey: ['permissions'],
    queryFn: () => apiGet<PermissionsResponse>('/roles/permissions'),
  });
}

export function useCreateRole() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: { name: string; permissions: Record<string, any>; field_permissions: Record<string, any> }) =>
      apiPost('/roles', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    },
  });
}

export function useUpdateRole() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: { name?: string; permissions?: Record<string, any>; field_permissions?: Record<string, any> } }) =>
      apiPatch(`/roles/${id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    },
  });
}

export function useDeleteRole() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => apiDelete(`/roles/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    },
  });
}
