/**
 * Role and permission hooks.
 */

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

// ── Types matching backend schemas ──

export interface Role {
  id: string;
  name: string;
  permissions: Record<string, boolean>;
  denied_permissions?: string[];
  field_permissions?: Record<string, Record<string, string>>;
  permission_version?: number;
}

export interface RoleListResponse {
  items: Role[];
}

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 interface RoleCreate {
  name: string;
  permissions: Record<string, boolean>;
  denied_permissions?: string[];
  field_permissions?: Record<string, Record<string, string>>;
}

export interface RoleUpdate {
  name?: string;
  permissions?: Record<string, boolean>;
  denied_permissions?: string[];
  field_permissions?: Record<string, Record<string, string>>;
}

export function useRoles() {
  return useQuery({
    queryKey: ['roles'],
    queryFn: async () => {
      const data = await apiGet<RoleListResponse>('/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: RoleCreate) =>
      apiPost('/roles', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['roles'] });
    },
  });
}

export function useUpdateRole() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: RoleUpdate }) =>
      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'] });
    },
  });
}
