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

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

export interface Prompt {
  id: string;
  mandateId: string;
  content: string;
  name: string;
  _createdBy?: string;
  _hideDelete?: boolean;
  [key: string]: any; // Allow additional properties
}

export interface AttributeOption {
  value: string | number;
  label: string | { [key: string]: string };
}

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

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;
  };
}

export interface CreatePromptData {
  name: string;
  content: string;
  // mandateId wird nicht mehr vom Client gesendet
  // Das Backend bestimmt den Kontext über die instanceId
}

export interface UpdatePromptData {
  name: string;
  content: string;
  // mandateId wird nicht mehr vom Client gesendet
}

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

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

/**
 * Fetch prompt attributes from backend
 * Endpoint: GET /api/attributes/Prompt
 */
export async function fetchPromptAttributes(_request: ApiRequestFunction): Promise<AttributeDefinition[]> {
  // Note: This uses api.get directly due to response format handling
  // For now, we'll use api.get directly in the hook as well
  throw new Error('fetchPromptAttributes should use api instance directly for response format handling');
}

/**
 * Fetch list of prompts with optional pagination
 * Endpoint: GET /api/prompts
 */
export async function fetchPrompts(
  request: ApiRequestFunction,
  params?: PaginationParams
): Promise<PaginatedResponse<Prompt> | Prompt[]> {
  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/prompts',
    method: 'get',
    params: requestParams
  });
  
  return data;
}

/**
 * Fetch a single prompt by ID
 * Endpoint: GET /api/prompts/{promptId}
 */
export async function fetchPromptById(
  request: ApiRequestFunction,
  promptId: string
): Promise<Prompt | null> {
  try {
    const data = await request({
      url: `/api/prompts/${promptId}`,
      method: 'get'
    });
    return data || null;
  } catch (error: any) {
    console.error('Error fetching prompt by ID:', error);
    return null;
  }
}

/**
 * Create a new prompt
 * Endpoint: POST /api/prompts
 */
export async function createPrompt(
  request: ApiRequestFunction,
  promptData: CreatePromptData
): Promise<Prompt> {
  return await request({
    url: '/api/prompts',
    method: 'post',
    data: promptData
  });
}

/**
 * Update a prompt
 * Endpoint: PUT /api/prompts/{promptId}
 */
export async function updatePrompt(
  request: ApiRequestFunction,
  promptId: string,
  promptData: UpdatePromptData
): Promise<Prompt> {
  return await request({
    url: `/api/prompts/${promptId}`,
    method: 'put',
    data: promptData
  });
}

/**
 * Delete a prompt
 * Endpoint: DELETE /api/prompts/{promptId}
 */
export async function deletePrompt(
  request: ApiRequestFunction,
  promptId: string
): Promise<void> {
  await request({
    url: `/api/prompts/${promptId}`,
    method: 'delete'
  });
}

