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

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

export interface AttributeDefinition {
  name: string;
  label: string;
  type: 'string' | 'number' | 'date' | 'boolean' | 'enum' | 'text' | 'email' | 'checkbox' | 'select' | 'multiselect' | 'textarea';
  sortable?: boolean;
  filterable?: boolean;
  searchable?: boolean;
  width?: number;
  minWidth?: number;
  maxWidth?: number;
  filterOptions?: string[];
  description?: string;
  required?: boolean;
  default?: any;
  options?: Array<{ value: string | number; label: string | { [key: string]: string } }> | string;
  validation?: any;
  ui?: any;
  readonly?: boolean;
  editable?: boolean;
  visible?: boolean;
  order?: number;
  placeholder?: string;
}

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

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

/**
 * Generic function to fetch attributes for any entity type
 * Endpoint: GET /api/attributes/{entityType}
 */
export async function fetchAttributes(
  request: ApiRequestFunction,
  entityType: string
): Promise<AttributeDefinition[]> {
  const data = await request({
    url: `/api/attributes/${entityType}`,
    method: 'get'
  }) as any;
  
  // Extract attributes from response - check if response.data.attributes exists, otherwise check if response.data is an array
  let attrs: AttributeDefinition[] = [];
  if (data?.attributes && Array.isArray(data.attributes)) {
    attrs = data.attributes;
  } else if (Array.isArray(data)) {
    attrs = data;
  } else if (data && typeof data === 'object') {
    // Try to find any array property in the response
    const keys = Object.keys(data);
    for (const key of keys) {
      if (Array.isArray(data[key])) {
        attrs = data[key];
        break;
      }
    }
  }
  
  return attrs;
}

/**
 * Fetch connection attributes from backend
 * Endpoint: GET /api/attributes/UserConnection
 */
export async function fetchConnectionAttributes(request: ApiRequestFunction): Promise<AttributeDefinition[]> {
  return fetchAttributes(request, 'UserConnection');
}

/**
 * Fetch file attributes from backend
 * Endpoint: GET /api/attributes/FileItem
 */
export async function fetchFileAttributes(request: ApiRequestFunction): Promise<AttributeDefinition[]> {
  const data = await request({
    url: '/api/attributes/FileItem',
    method: 'get'
  }) as AttributeDefinition[] | { attributes: AttributeDefinition[] };
  
  // Handle different response formats
  if (Array.isArray(data)) {
    return data;
  }
  if (data && typeof data === 'object' && 'attributes' in data && Array.isArray(data.attributes)) {
    return data.attributes;
  }
  
  // Try to find any array property in the response
  if (data && typeof data === 'object') {
    const keys = Object.keys(data);
    for (const key of keys) {
      if (Array.isArray((data as any)[key])) {
        return (data as any)[key];
      }
    }
  }
  
  return [];
}

/**
 * Fetch prompt attributes from backend
 * Endpoint: GET /api/attributes/Prompt
 */
export async function fetchPromptAttributes(request: ApiRequestFunction): Promise<AttributeDefinition[]> {
  return fetchAttributes(request, 'Prompt');
}

/**
 * Fetch user attributes from backend
 * Endpoint: GET /api/attributes/User
 */
export async function fetchUserAttributes(request: ApiRequestFunction): Promise<AttributeDefinition[]> {
  return fetchAttributes(request, 'User');
}

/**
 * Fetch workflow attributes from backend
 * Endpoint: GET /api/attributes/ChatWorkflow
 */
export async function fetchWorkflowAttributes(request: ApiRequestFunction): Promise<AttributeDefinition[]> {
  return fetchAttributes(request, 'ChatWorkflow');
}
