import { apiClient } from '@/lib/api-client';
import { PaginatedResponse } from '@edr/types';

// Export apiClient for direct use
export { apiClient };

// Bookings API
export const bookingsApi = {
  getAll: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([_, value]) => value !== '' && value !== undefined && value !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/bookings${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getById: (id: string) => apiClient.get<any>(`/bookings/${id}`),
  getMy: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([_, value]) => value !== '' && value !== undefined && value !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/bookings/my${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getByDevice: async (deviceId: string, params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries({ ...params }).filter(([_, value]) => value !== '' && value !== undefined && value !== null)
    ) as Record<string, string>;
    cleanParams['deviceId'] = deviceId;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/bookings/by-device${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  cancel: (id: string, data?: any) => apiClient.post<any>(`/bookings/${id}/cancel`, data),
  modify: (id: string, data: any) => apiClient.patch<any>(`/bookings/${id}`, data),
  checkUsage: (id: string) => apiClient.get<any>(`/bookings/${id}/usage`),
  forceConfirm: (bookingId: string, data: { paymentReference?: string; paymentMethod?: string; notes?: string }) =>
    apiClient.post<any>(`/payments/${bookingId}/force-confirm`, data),
  smartAssign: (bookingId: string) =>
    apiClient.post<any>(`/tickets/smart-assign/${bookingId}`, {}),
  // Converts a reserved (blocked) seat into a real booking — STAFF (fee-waived, ticket
  // issued immediately) or PASSENGER (payment link texted to the traveler's phone).
  issueFromReservation: (seatId: string, data: any) =>
    apiClient.post<any>(`/bookings/reservations/${seatId}/issue`, data),
};

// Passengers API
export const passengersApi = {
  getAll: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([_, value]) => value !== '' && value !== undefined && value !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/passengers${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getById: (id: string) => apiClient.get<any>(`/passengers/${id}`),
  verify: (nationalId: string) => apiClient.post<any>('/passengers/verify-fayda', { nationalId }),
  delete: (id: string, cascade?: boolean) => apiClient.delete(`/passengers/${id}${cascade ? '?cascade=true' : ''}`),
};
// Stations API
export const stationsApi = {
  getAll: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([_, value]) => value !== '' && value !== undefined && value !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/stations${query ? `?${query}` : ''}`);
    // Handle wrapped response: { success, data: [...], timestamp }
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getById: (id: string) => apiClient.get<any>(`/stations/${id}`),
  create: (data: any) => apiClient.post<any>('/stations', data),
  update: (id: string, data: any) => apiClient.patch<any>(`/stations/${id}`, data),
  delete: (id: string, cascade?: boolean) => apiClient.delete(`/stations/${id}${cascade ? '?cascade=true' : ''}`),
};

// Fleet API
export const fleetApi = {
  getTrains: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([_, value]) => value !== '' && value !== undefined && value !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/fleet/trains${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getCoaches: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([_, value]) => value !== '' && value !== undefined && value !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/fleet/coaches${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  createTrain: (data: any) => apiClient.post<any>('/fleet/trains', data),
  updateTrain: (id: string, data: any) => apiClient.patch<any>(`/fleet/trains/${id}`, data),
  deleteTrain: (id: string, cascade?: boolean) => apiClient.delete(`/fleet/trains/${id}${cascade ? '?cascade=true' : ''}`),
  restoreTrain: (id: string) => apiClient.patch<any>(`/fleet/trains/${id}/restore`, {}),
  createCoach: (data: any) => apiClient.post<any>('/fleet/coaches', data),
  updateCoach: (id: string, data: any) => apiClient.patch<any>(`/fleet/coaches/${id}`, data),
  deleteCoach: (id: string, cascade?: boolean) => apiClient.delete(`/fleet/coaches/${id}${cascade ? '?cascade=true' : ''}`),
  generateSeatMap: (data: any) => apiClient.post<any>('/fleet/seatmap/generate', data),
  getCoach: (id: string) => apiClient.get<any>(`/fleet/coaches/${id}`),
};

// Schedules API
export const schedulesApi = {
  getAll: async (params?: any) => {
    const query = new URLSearchParams(params as Record<string, string>).toString();
    const response = await apiClient.get<any>(`/schedules${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getById: (id: string) => apiClient.get<any>(`/schedules/${id}`),
  create: (data: any) => apiClient.post<any>('/schedules', data),
  update: (id: string, data: any) => apiClient.patch<any>(`/schedules/${id}`, data),
  delete: (id: string) => apiClient.delete(`/schedules/${id}`),
  updateStatus: (id: string, status: string) => apiClient.patch<any>(`/schedules/${id}/status`, { status }),
  assignCoaches: (scheduleId: string, coaches: Array<{ coachId: string; positionNumber: number }>) =>
    apiClient.post<any>(`/schedules/${scheduleId}/coaches`, { coaches }),
  getAssignedCoaches: (scheduleId: string) => apiClient.get<any>(`/schedules/${scheduleId}/coaches`),
  removeCoachAssignment: (scheduleId: string, coachId: string) =>
    apiClient.delete(`/schedules/${scheduleId}/coaches/${coachId}`),
};

// Seats API
export const seatsApi = {
  getSeatMap: (scheduleId: string, coachId?: string) => {
    const params = coachId ? `?coachId=${coachId}` : '';
    return apiClient.get<any>(`/seats/seatmap/${scheduleId}${params}`);
  },
  getBySchedule: (scheduleId: string) => apiClient.get<any>(`/seats/schedule/${scheduleId}`),
  getBlocked: () => apiClient.get<any[]>('/seats/blocks'),
  hold: (data: any) => apiClient.post<any>('/seats/hold', data),
  release: (holdId: string) => apiClient.delete(`/seats/hold/${holdId}`),
  block: (seatId: string, data: any) => apiClient.post<any>(`/seats/${seatId}/block`, data),
  unblock: (seatId: string, scheduleId?: string) => apiClient.delete(`/seats/${seatId}/block${scheduleId ? `?scheduleId=${scheduleId}` : ''}`),
  removeSeat: (seatId: string) => apiClient.patch<any>(`/seats/${seatId}/remove`, {}),
  undoRemove: (seatId: string) => apiClient.patch<any>(`/seats/${seatId}/undo-remove`, {}),
  setMaintenance: (seatId: string, reason: string) => apiClient.post<any>(`/seats/${seatId}/maintenance`, { reason }),
  clearMaintenance: (seatId: string) => apiClient.delete(`/seats/${seatId}/maintenance`),
  getDuplicates: (date: string, scheduleId?: string) =>
    apiClient.get<any>(`/seats/duplicates?date=${date}${scheduleId ? `&scheduleId=${scheduleId}` : ''}`),
  resolveDuplicates: (data: { bookingSeatIds: string[]; coachIds: string[] }) =>
    apiClient.post<any>('/seats/duplicates/resolve', data),
};

// Payments API
export const paymentsApi = {
  getAll: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([, v]) => v !== '' && v !== undefined && v !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/payments/all${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getById: (id: string) => apiClient.get<any>(`/payments/${id}`),
  refund: (id: string, data: any) => apiClient.post<any>(`/payments/${id}/refund`, data),
  getProviders: () => apiClient.get<any[]>('/payments/providers'),
  getMethods: async () => {
    const response = await apiClient.get('/payments/methods');
    return (response as any)?.data || response || [];
  },
  addMethod: (data: any) => apiClient.post('/payments/methods', data),
  updateMethod: (id: string, data: any) => apiClient.patch(`/payments/methods/${id}`, data),
  deleteMethod: (id: string) => apiClient.delete(`/payments/methods/${id}`),
  supplementary: {
    create: (data: { bookingRef: string; amountMinor: number; reason: string; notes?: string }) =>
      apiClient.post<any>('/payments/supplementary', data),
    getAll: async (params?: any) => {
      const cleanParams = Object.fromEntries(
        Object.entries(params || {}).filter(([, v]) => v !== '' && v !== undefined && v !== null)
      ) as Record<string, string>;
      const query = new URLSearchParams(cleanParams).toString();
      const response = await apiClient.get<any>(`/payments/supplementary${query ? `?${query}` : ''}`);
      if ((response as any)?.data) return (response as any).data;
      return response;
    },
    markPaid: (id: string, providerTxnId?: string) =>
      apiClient.post<any>(`/payments/supplementary/${id}/mark-paid`, { providerTxnId }),
    waive: (id: string, notes?: string) =>
      apiClient.post<any>(`/payments/supplementary/${id}/waive`, { notes }),
    resend: (id: string) =>
      apiClient.post<any>(`/payments/supplementary/${id}/resend`, {}),
  },
};

// Tickets API
export const ticketsApi = {
  getAll: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([_, value]) => value !== '' && value !== undefined && value !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/tickets${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getById: (id: string) => apiClient.get<any>(`/tickets/${id}`),
  generateMissing: (limit = 10) => apiClient.post<any>(`/tickets/generate-missing?limit=${limit}`, {}),
  validate: (ticketId: string, data: any) => apiClient.post<any>(`/tickets/${ticketId}/validate`, data),
  scanAndBoard: (qrCodeOrRef: string, data: any) => apiClient.post<any>(`/tickets/scan-board/${encodeURIComponent(qrCodeOrRef)}`, data),
  regenerate: (ticketId: string) => apiClient.post<any>(`/tickets/${ticketId}/regenerate`),
};

// Agents API
export const agentsApi = {
  getAll: async (params?: any) => {
    const query = new URLSearchParams(params as Record<string, string>).toString();
    const response = await apiClient.get<any>(`/agents${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getById: (id: string) => apiClient.get<any>(`/agents/${id}`),
  create: (data: any) => apiClient.post<any>('/agents', data),
  update: (id: string, data: any) => apiClient.patch<any>(`/agents/${id}`, data),
  delete: (id: string) => apiClient.delete(`/agents/${id}`),
  getShifts: (agentId: string) => apiClient.get<any[]>(`/agents/${agentId}/shifts`),
  openShift: (agentId: string, data: any) => apiClient.post<any>(`/agents/${agentId}/shifts/open`, data),
  closeShift: (shiftId: string, data: any) => apiClient.post<any>(`/agents/shifts/${shiftId}/close`, data),
  getCommissions: (agentId: string) => apiClient.get<any[]>(`/agents/${agentId}/commissions`),
};

// Loyalty API
export const loyaltyApi = {
  getAccounts: async (params?: any) => {
    const query = new URLSearchParams(params as Record<string, string>).toString();
    const response = await apiClient.get<any>(`/loyalty/accounts${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getAccount: (passengerId: string) => apiClient.get<any>(`/loyalty/accounts/${passengerId}`),
  adjustPoints: (accountId: string, data: any) => apiClient.post<any>(`/loyalty/accounts/${accountId}/adjust`, data),
  getRewards: () => apiClient.get<any[]>('/loyalty/rewards'),
  createReward: (data: any) => apiClient.post<any>('/loyalty/rewards', data),
  delete: (id: string) => apiClient.delete(`/loyalty/accounts/${id}`),
};

// Wallet API
export const walletApi = {
  getAccounts: async (params?: any) => {
    const query = new URLSearchParams(params as Record<string, string>).toString();
    const response = await apiClient.get<any>(`/wallet/accounts${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getAccount: (passengerId: string) => apiClient.get<any>(`/wallet/accounts/${passengerId}`),
  adjustBalance: (accountId: string, data: any) => apiClient.post<any>(`/wallet/accounts/${accountId}/adjust`, data),
  getLedger: (accountId: string) => apiClient.get<any[]>(`/wallet/accounts/${accountId}/ledger`),
  delete: (id: string) => apiClient.delete(`/wallet/accounts/${id}`),
};

// Promotions API
export const promotionsApi = {
  getAll: async (params?: any) => {
    const query = new URLSearchParams(params as Record<string, string>).toString();
    const response = await apiClient.get<any>(`/promos${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getById: (id: string) => apiClient.get<any>(`/promos/${id}`),
  create: (data: any) => apiClient.post<any>('/promos', data),
  update: (id: string, data: any) => apiClient.patch<any>(`/promos/${id}`, data),
  delete: (id: string) => apiClient.delete(`/promos/${id}`),
};

export { promosApi } from './promos';
export { usersApi } from './users';

// Support API
export const supportApi = {
  getConversations: async (params?: any) => {
    const query = new URLSearchParams(params as Record<string, string>).toString();
    const response = await apiClient.get<any>(`/support/conversations${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getConversation: (id: string) => apiClient.get<any>(`/support/conversations/${id}`),
  updateStatus: (id: string, status: string) => apiClient.patch<any>(`/support/conversations/${id}/status`, { status }),
  sendMessage: (conversationId: string, data: any) => apiClient.post<any>(`/support/conversations/${conversationId}/messages`, data),
  getFaqs: () => apiClient.get<any[]>('/support/faqs'),
  createFaq: (data: any) => apiClient.post<any>('/support/faqs', data),
};

// Notifications API
export const notificationsApi = {
  getTemplates: () => apiClient.get<any[]>('/notifications/templates'),
  createTemplate: (data: any) => apiClient.post<any>('/notifications/templates', data),
  updateTemplate: (id: string, data: any) => apiClient.patch<any>(`/notifications/templates/${id}`, data),
  send: (data: any) => apiClient.post<any>('/notifications/send', data),
  getHistory: async (params?: any) => {
    const query = new URLSearchParams(params as Record<string, string>).toString();
    const response = await apiClient.get<any>(`/notifications/history${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
};

// Fraud API
export const fraudApi = {
  getAlerts: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([, v]) => v !== '' && v !== undefined && v !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/fraud/alerts${query ? `?${query}` : ''}`);
    // Backend returns { data: [...], total } or { items: [...] }
    const arr = (response as any)?.data ?? (response as any)?.items ?? response;
    return { items: Array.isArray(arr) ? arr : [] };
  },
  acknowledgeAlert: (id: string) => apiClient.patch<any>(`/fraud/alerts/${id}/acknowledge`),
  getRules: () => apiClient.get<any[]>('/fraud/rules'),
  updateRule: (id: string, data: any) => apiClient.patch<any>(`/fraud/rules/${id}`, data),
  blockUser: (userId: string, data: any) => apiClient.post<any>(`/fraud/users/${userId}/block`, data),
};

// Verifayda API
export const verifaydaApi = {
  getVerifications: async (params?: any) => {
    const query = new URLSearchParams(params as Record<string, string>).toString();
    const response = await apiClient.get<any>(`/passengers/verifications${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  verify: (nationalId: string) => apiClient.post<any>('/passengers/verify-fayda', { nationalId }),
  getStats: () => apiClient.get<any>('/passengers/verification-stats'),
};

// Audit API
export const auditApi = {
  getLogs: async (params?: any) => {
    const query = new URLSearchParams(params as Record<string, string>).toString();
    const response = await apiClient.get<any>(`/audit/logs${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  getLog: (id: string) => apiClient.get<any>(`/audit/logs/${id}`),
};

// Live Tracking API
export const liveApi = {
  getTrips: () => apiClient.get<any[]>('/live/trips'),
  getTrip: (tripId: string) => apiClient.get<any>(`/live/trips/${tripId}`),
  updateLocation: (tripId: string, data: any) => apiClient.post<any>(`/live/trips/${tripId}/location`, data),
  getCrowdSignals: () => apiClient.get<any[]>('/live/crowd-signals'),
};

// Classes API (formerly Seat Classes)
export const seatClassesApi = {
  getAll: () => apiClient.get<any[]>('/fleet/classes'),
  getById: (id: string) => apiClient.get<any>(`/fleet/classes/${id}`),
  create: (data: any) => apiClient.post<any>('/fleet/classes', data),
  update: (id: string, data: any) => apiClient.patch<any>(`/fleet/classes/${id}`, data),
  delete: (id: string, cascade?: boolean) => apiClient.delete(`/fleet/classes/${id}${cascade ? '?cascade=true' : ''}`),
};

// Food & Dining API
export const foodApi = {
  getCategories: () => apiClient.get<any[]>('/food/categories'),
  getMenuItems: (scheduleId: string) => apiClient.get<any[]>(`/food/menu/${scheduleId}`),
  getOrders: async (params?: any) => {
    const query = new URLSearchParams(params as Record<string, string>).toString();
    const response = await apiClient.get<any>(`/food/orders${query ? `?${query}` : ''}`);
    if (response?.data) {
      return Array.isArray(response.data) ? { items: response.data } : response;
    }
    return Array.isArray(response) ? { items: response } : response;
  },
  updateOrderStatus: (orderId: string, status: string) => apiClient.patch<any>(`/food/orders/${orderId}/status`, { status }),
  createMenuItem: (data: any) => apiClient.post<any>('/food/menu-items', data),
};

// Reports API
export const reportsApi = {
  generateReport: (data: any) => apiClient.post<any>('/reports/generate', data),
  getReport: (reportId: string) => apiClient.get<any>(`/reports/${reportId}`),
  listReports: async (reportType?: string) => {
    const query = reportType ? `?type=${reportType}` : '';
    const response = await apiClient.get<any>(`/reports${query}`);
    if (Array.isArray(response)) return { items: response };
    return (response as any)?.data ? (Array.isArray((response as any).data) ? { items: (response as any).data } : response) : { items: [] };
  },
};

// Packages API
export const packagesApi = {
  getAll: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([_, value]) => value !== '' && value !== undefined && value !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/packages/all${query ? `?${query}` : ''}`);
    if ((response as any)?.data) return Array.isArray((response as any).data) ? { items: (response as any).data } : response;
    return Array.isArray(response) ? { items: response } : response;
  },
  getById: (id: string) => apiClient.get<any>(`/packages/${id}`),
  create: (data: any) => apiClient.post<any>('/packages', data),
  update: (id: string, data: any) => apiClient.patch<any>(`/packages/${id}`, data),
  activate: (id: string) => apiClient.patch<any>(`/packages/${id}/activate`, {}),
  deactivate: (id: string) => apiClient.patch<any>(`/packages/${id}/deactivate`, {}),
  remove: (id: string, cascade?: boolean) => apiClient.delete(`/packages/${id}${cascade ? '?cascade=true' : ''}`),
  getBookings: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([_, value]) => value !== '' && value !== undefined && value !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/packages/bookings${query ? `?${query}` : ''}`);
    if ((response as any)?.data) return Array.isArray((response as any).data) ? { items: (response as any).data } : response;
    return Array.isArray(response) ? { items: response } : response;
  },
  addTier: (packageId: string, data: any) => apiClient.post<any>(`/packages/${packageId}/tiers`, data),
  updateTier: (tierId: string, data: any) => apiClient.patch<any>(`/packages/tiers/${tierId}`, data),
  deleteTier: (tierId: string) => apiClient.delete(`/packages/tiers/${tierId}`),
};

// Package Inquiries API
export const packageInquiriesApi = {
  getAll: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([_, v]) => v !== '' && v !== undefined && v !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/packages/inquiries${query ? `?${query}` : ''}`);
    if ((response as any)?.data) return Array.isArray((response as any).data) ? { items: (response as any).data } : response;
    return Array.isArray(response) ? { items: response } : response;
  },
  create: (data: any) => apiClient.post<any>('/packages/inquiries', data),
  updateStatus: (id: string, status: string) => apiClient.patch<any>(`/packages/inquiries/${id}/status`, { status }),
  remove: (id: string) => apiClient.delete(`/packages/inquiries/${id}`),
};

// Excess Luggage API
export const excessBaggageApi = {
  logCharge: (data: any) => apiClient.post<any>('/agents/excess-baggage', data),
  getCharge: (id: string) => apiClient.get<any>(`/agents/excess-baggage/${id}`),
  getAll: async (params?: any) => {
    const cleanParams = Object.fromEntries(
      Object.entries(params || {}).filter(([_, v]) => v !== '' && v !== undefined && v !== null)
    ) as Record<string, string>;
    const query = new URLSearchParams(cleanParams).toString();
    const response = await apiClient.get<any>(`/agents/excess-baggage${query ? `?${query}` : ''}`);
    if ((response as any)?.data) return Array.isArray((response as any).data) ? { items: (response as any).data } : response;
    return Array.isArray(response) ? { items: response } : response;
  },
  resendLink: (id: string) => apiClient.post<any>(`/agents/excess-baggage/${id}/resend`, {}),
  waive: (id: string, data: any) => apiClient.patch<any>(`/agents/excess-baggage/${id}/waive`, data),
  delete: (id: string) => apiClient.delete(`/agents/excess-baggage/${id}`),
};

// Segment Fares API
export const segmentFaresApi = {
  getAll: (routeId?: string) => apiClient.get<any>(`/admin/segment-fares${routeId ? `?routeId=${routeId}` : ''}`),
  create: (data: any) => apiClient.post<any>('/admin/segment-fares', data),
  update: (id: string, data: any) => apiClient.put<any>(`/admin/segment-fares/${id}`, data),
  remove: (id: string) => apiClient.delete(`/admin/segment-fares/${id}`),
};

// Route Coach Templates API
export const routeCoachTemplatesApi = {
  get: (routeId: string) => apiClient.get<any>(`/routes/${routeId}/coaches`),
  set: (routeId: string, coaches: Array<{ coachId: string; positionNumber: number }>) =>
    apiClient.put<any>(`/routes/${routeId}/coaches`, { coaches }),
  clear: (routeId: string) => apiClient.delete(`/routes/${routeId}/coaches`),
};

// System Config API
export const systemConfigApi = {
  getAll: () => apiClient.get<Record<string, string>>('/config'),
  update: (data: Record<string, string>) => apiClient.patch<Record<string, string>>('/config', data),
};

// App Releases API
export const appReleasesApi = {
  getAll: async () => {
    const response = await apiClient.get<any>('/app-releases');
    return Array.isArray(response) ? response : (response as any)?.items || (response as any)?.data || [];
  },
  create: (data: any) => apiClient.post<any>('/app-releases', data),
  update: (id: string, data: any) => apiClient.patch<any>(`/app-releases/${id}`, data),
  remove: (id: string) => apiClient.delete(`/app-releases/${id}`),
};
