// composables/useVisitAPI.ts

export interface VisitStats {
  today_patients: number;
  today_active_queues_by_service: Record<string, number>;
  average_waiting_seconds: number;
  monthly_trend: Array<{
    count: number;
    month: string;
    payment_type: string;
  }>;
  total_by_payment_type: Record<string, number>;
  payment_type_distribution_percent: Record<string, number>;
  average_waiting_by_service_seconds: Record<string, number>;
  from: string;
  to: string;
}

export const useVisitAPI = () => {
  const config = useRuntimeConfig();
  // We use the configured proxy path to avoid CORS issues
  const statsURL = '/stats-api/visit/stats';

  /**
   * Fetch visit statistics
   */
  const fetchStats = async (filters: { from?: string; to?: string; service_code?: string; payment_type?: string } = {}): Promise<VisitStats | null> => {
    try {
      const queryParams = new URLSearchParams();
      if (filters.from) queryParams.append('from', filters.from);
      if (filters.to) queryParams.append('to', filters.to);
      if (filters.service_code) queryParams.append('service_code', filters.service_code);
      if (filters.payment_type) queryParams.append('payment_type', filters.payment_type);

      const url = `${statsURL}${queryParams.toString() ? '?' + queryParams.toString() : ''}`;
      
      const response = await $fetch<{ message: string; data: VisitStats }>(url, {
        method: 'GET',
      });

      if (response && response.data) {
        return response.data;
      }
      return null;
    } catch (error: any) {
      console.error('❌ Error fetching visit stats:', error);
      return null;
    }
  };

  return {
    fetchStats,
  };
};
