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

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

export interface RbacRule {
  id: string;
  [key: string]: any; // Allow additional properties from backend
}

export type RbacRuleUpdateData = Partial<Omit<RbacRule, 'id'>>;

export interface PaginationParams {
  page?: number;
  pageSize?: number;
  sort?: Array<{ field: string; direction: 'asc' | 'desc' }>;
  filters?: Record<string, any>;
  search?: string;
}

export interface PaginatedResponse<T> {
  items: T[];
  pagination?: {
    currentPage: number;
    pageSize: number;
    totalItems: number;
    totalPages: number;
  };
}

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

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

/**
 * Fetch list of RBAC rules with optional pagination
 * Endpoint: GET /api/rbac/rules
 */
export async function fetchRbacRules(
  request: ApiRequestFunction,
  params?: PaginationParams
): Promise<PaginatedResponse<RbacRule> | RbacRule[]> {
  const requestParams: any = {};
  
  // Build pagination object if provided
  if (params) {
    const paginationObj: any = {};
    
    if (params.page !== undefined) paginationObj.page = params.page;
    if (params.pageSize !== undefined) paginationObj.pageSize = params.pageSize;
    if (params.sort) paginationObj.sort = params.sort;
    if (params.filters) paginationObj.filters = params.filters;
    if (params.search) paginationObj.search = params.search;
    
    if (Object.keys(paginationObj).length > 0) {
      requestParams.pagination = JSON.stringify(paginationObj);
    }
  }
  
  const data = await request({
    url: '/api/rbac/rules',
    method: 'get',
    params: requestParams
  });
  
  return data;
}

/**
 * Fetch a single RBAC rule by ID
 * Endpoint: GET /api/rbac/rules/{ruleId}
 */
export async function fetchRbacRuleById(
  request: ApiRequestFunction,
  ruleId: string
): Promise<RbacRule | null> {
  try {
    const data = await request({
      url: `/api/rbac/rules/${ruleId}`,
      method: 'get'
    });
    return data || null;
  } catch (error: any) {
    console.error('Error fetching RBAC rule by ID:', error);
    return null;
  }
}

/**
 * Update a RBAC rule
 * Endpoint: PUT /api/rbac/rules/{ruleId}
 */
export async function updateRbacRule(
  request: ApiRequestFunction,
  ruleId: string,
  updateData: RbacRuleUpdateData
): Promise<RbacRule> {
  return await request({
    url: `/api/rbac/rules/${ruleId}`,
    method: 'put',
    data: updateData
  });
}

/**
 * Create a new RBAC rule
 * Endpoint: POST /api/rbac/rules
 */
export async function createRbacRule(
  request: ApiRequestFunction,
  ruleData: Partial<RbacRule>
): Promise<RbacRule> {
  return await request({
    url: '/api/rbac/rules',
    method: 'post',
    data: ruleData
  });
}

/**
 * Delete a RBAC rule
 * Endpoint: DELETE /api/rbac/rules/{ruleId}
 */
export async function deleteRbacRule(
  request: ApiRequestFunction,
  ruleId: string
): Promise<void> {
  await request({
    url: `/api/rbac/rules/${ruleId}`,
    method: 'delete'
  });
}
