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

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

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

export type MandateUpdateData = Partial<Omit<Mandate, '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 mandates with optional pagination
 * Endpoint: GET /api/mandates/
 */
export async function fetchMandates(
  request: ApiRequestFunction,
  params?: PaginationParams
): Promise<PaginatedResponse<Mandate> | Mandate[]> {
  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/mandates/',
    method: 'get',
    params: requestParams
  });
  
  return data;
}

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

/**
 * Update a mandate
 * Endpoint: PUT /api/mandates/{mandateId}
 */
export async function updateMandate(
  request: ApiRequestFunction,
  mandateId: string,
  updateData: MandateUpdateData
): Promise<Mandate> {
  return await request({
    url: `/api/mandates/${mandateId}`,
    method: 'put',
    data: updateData
  });
}

/**
 * Create a new mandate
 * Endpoint: POST /api/mandates/
 */
export async function createMandate(
  request: ApiRequestFunction,
  mandateData: Partial<Mandate>
): Promise<Mandate> {
  return await request({
    url: '/api/mandates/',
    method: 'post',
    data: mandateData
  });
}

/**
 * Delete a mandate
 * Endpoint: DELETE /api/mandates/{mandateId}
 */
export async function deleteMandate(
  request: ApiRequestFunction,
  mandateId: string
): Promise<void> {
  await request({
    url: `/api/mandates/${mandateId}`,
    method: 'delete'
  });
}
