import { ApiRequestOptions } from '../hooks/useApi';

// ============================================================================
// TYPES & INTERFACES
// ============================================================================

export type PermissionLevel = 'n' | 'o' | 'a';

export interface UserPermissions {
  view: boolean;
  read: PermissionLevel;
  create: PermissionLevel;
  update: PermissionLevel;
  delete: PermissionLevel;
}

export type PermissionContext = 'DATA' | 'UI' | 'RESOURCE';

// Response type for bulk permissions fetch
export interface BulkPermissionsResponse {
  ui?: Record<string, UserPermissions>;
  resource?: Record<string, UserPermissions>;
}

// Type for the request function passed to API functions
export type ApiRequestFunction = (options: ApiRequestOptions<any>) => Promise<any>;

// ============================================================================
// API REQUEST FUNCTIONS
// ============================================================================

/**
 * Fetch permissions for a given context and item
 * Endpoint: GET /api/rbac/permissions
 * Query params: context (required), item (optional)
 */
export async function fetchPermissions(
  request: ApiRequestFunction,
  context: PermissionContext,
  item?: string
): Promise<UserPermissions> {
  const params: Record<string, string> = { context };
  if (item) {
    params.item = item;
  }
  
  const data = await request({
    url: '/api/rbac/permissions',
    method: 'get',
    params
  });
  
  return data;
}

/**
 * Fetch all permissions for a given context (UI or RESOURCE)
 * Endpoint: GET /api/rbac/permissions/all
 * Query params: context (optional - if not provided, returns both UI and RESOURCE)
 * 
 * This is optimized for UI initialization to avoid multiple API calls.
 * Returns a dictionary of item paths to their permissions.
 */
export async function fetchAllPermissions(
  request: ApiRequestFunction,
  context?: 'UI' | 'RESOURCE'
): Promise<BulkPermissionsResponse> {
  const params: Record<string, string> = {};
  if (context) {
    params.context = context;
  }
  
  console.log('📡 fetchAllPermissions: Fetching all permissions:', {
    context: context || 'all',
    url: '/api/rbac/permissions/all'
  });
  
  const data = await request({
    url: '/api/rbac/permissions/all',
    method: 'get',
    params
  });
  
  console.log('📥 fetchAllPermissions: Received bulk permissions:', {
    context: context || 'all',
    uiItemCount: data?.ui ? Object.keys(data.ui).length : 0,
    resourceItemCount: data?.resource ? Object.keys(data.resource).length : 0
  });
  
  return data;
}

