/*
 * File: aiPredictionAPI.ts
 * Description: API service for AI prediction operations using apisauce
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */

import { create } from 'apisauce';
import { API_CONFIG, buildHeaders } from '../../../shared/utils';

const api = create({
  baseURL: API_CONFIG.BASE_URL
});

/**
 * AI Prediction API Service
 * 
 * Purpose: Handle all AI prediction-related API operations
 * 
 * Features:
 * - Get AI prediction results for all patients
 * - Get individual case prediction details
 * - Update case review status
 * - Search and filter predictions
 * - Get prediction statistics
 */
export const aiPredictionAPI = {
  /**
   * Get All AI Prediction Results
   * 
   * Purpose: Fetch all AI prediction results from server
   * 
   * @param token - Authentication token
   * @param params - Optional query parameters for filtering
   * @returns Promise with AI prediction cases data
   */
  getAllPredictions: (token: string, params?: {
    page?: number;
    limit?: number;
    urgency?: string;
    severity?: string;
    category?: string;
    search?: string;
  }) => {
    const queryParams = params ? { ...params } : {};
    return api.get('/api/ai-cases/all-prediction-results', queryParams, buildHeaders({ token }));
  },

  /**
   * Get AI Prediction Case Details
   * 
   * Purpose: Fetch detailed information for a specific AI prediction case
   * 
   * @param caseId - AI prediction case ID (patid)
   * @param token - Authentication token
   * @returns Promise with detailed case prediction data
   */
  getCaseDetails: (caseId: string, token: string) => {
    return api.get(`/api/ai-cases/prediction-details/${caseId}`, {}, buildHeaders({ token }));
  },

  /**
   * Update Case Review Status
   * 
   * Purpose: Update the review status of an AI prediction case
   * 
   * @param caseId - AI prediction case ID
   * @param reviewData - Review status and notes
   * @param token - Authentication token
   * @returns Promise with updated case data
   */
  updateCaseReview: (caseId: string, reviewData: {
    review_status: 'pending' | 'reviewed' | 'confirmed' | 'disputed';
    reviewed_by?: string;
    review_notes?: string;
    priority?: 'critical' | 'high' | 'medium' | 'low';
  }, token: string) => {
    return api.put(`/api/ai-cases/review/${caseId}`, reviewData, buildHeaders({ token }));
  },

  /**
   * Get Prediction Statistics
   * 
   * Purpose: Fetch AI prediction statistics for dashboard
   * 
   * @param token - Authentication token
   * @param timeRange - Optional time range filter (today, week, month)
   * @returns Promise with prediction statistics
   */
  getPredictionStats: (token: string, timeRange?: 'today' | 'week' | 'month') => {
    const params = timeRange ? { timeRange } : {};
    return api.get('/api/ai-cases/statistics', params, buildHeaders({ token }));
  },

  /**
   * Search AI Prediction Cases
   * 
   * Purpose: Search AI prediction cases by various criteria
   * 
   * @param query - Search query (patient ID, hospital, findings)
   * @param token - Authentication token
   * @param filters - Additional search filters
   * @returns Promise with search results
   */
  searchPredictions: (query: string, token: string, filters?: {
    urgency?: string[];
    severity?: string[];
    category?: string[];
    dateRange?: { start: string; end: string };
  }) => {
    const params = {
      q: query,
      ...(filters && { filters: JSON.stringify(filters) })
    };
    return api.get('/api/ai-cases/search', params, buildHeaders({ token }));
  },

  /**
   * Get Predictions by Hospital
   * 
   * Purpose: Fetch AI predictions filtered by hospital
   * 
   * @param hospitalId - Hospital UUID
   * @param token - Authentication token
   * @param params - Optional query parameters
   * @returns Promise with hospital-specific predictions
   */
  getPredictionsByHospital: (hospitalId: string, token: string, params?: {
    page?: number;
    limit?: number;
    urgency?: string;
    startDate?: string;
    endDate?: string;
  }) => {
    const queryParams = params ? { ...params } : {};
    return api.get(`/api/ai-cases/hospital/${hospitalId}/predictions`, queryParams, buildHeaders({ token }));
  },

  /**
   * Get Critical Predictions
   * 
   * Purpose: Fetch only critical and urgent AI predictions
   * 
   * @param token - Authentication token
   * @returns Promise with critical predictions data
   */
  getCriticalPredictions: (token: string) => {
    return api.get('/api/ai-cases/critical-predictions', {}, buildHeaders({ token }));
  },

  /**
   * Bulk Update Case Reviews
   * 
   * Purpose: Update multiple case reviews at once
   * 
   * @param caseIds - Array of case IDs to update
   * @param reviewData - Review data to apply to all cases
   * @param token - Authentication token
   * @returns Promise with bulk update results
   */
  bulkUpdateReviews: (caseIds: string[], reviewData: {
    review_status: 'pending' | 'reviewed' | 'confirmed' | 'disputed';
    reviewed_by?: string;
    review_notes?: string;
  }, token: string) => {
    return api.put('/api/ai-cases/bulk-review', { 
      caseIds, 
      reviewData 
    }, buildHeaders({ token }));
  },

  /**
   * Export Predictions Data
   * 
   * Purpose: Export AI predictions data for reporting
   * 
   * @param token - Authentication token
   * @param filters - Export filters
   * @param format - Export format (csv, xlsx, pdf)
   * @returns Promise with export file data
   */
  exportPredictions: (token: string, filters?: {
    urgency?: string[];
    severity?: string[];
    dateRange?: { start: string; end: string };
    hospitalId?: string;
  }, format: 'csv' | 'xlsx' | 'pdf' = 'csv') => {
    const params = {
      format,
      ...(filters && { filters: JSON.stringify(filters) })
    };
    return api.get('/api/ai-cases/export', params, buildHeaders({ token }));
  },

  /**
   * Get Prediction Trends
   * 
   * Purpose: Fetch prediction trends data for analytics
   * 
   * @param token - Authentication token
   * @param period - Time period for trends (daily, weekly, monthly)
   * @returns Promise with trends data
   */
  getPredictionTrends: (token: string, period: 'daily' | 'weekly' | 'monthly' = 'weekly') => {
    return api.get('/api/ai-cases/trends', { period }, buildHeaders({ token }));
  },

  /**
   * Submit Feedback on Prediction
   * 
   * Purpose: Submit physician feedback on AI prediction accuracy
   * 
   * @param caseId - AI prediction case ID
   * @param feedbackData - Feedback data
   * @param token - Authentication token
   * @returns Promise with feedback submission result
   */
  submitPredictionFeedback: (caseId: string, feedbackData: {
    accuracy_rating: 1 | 2 | 3 | 4 | 5;
    is_accurate: boolean;
    physician_diagnosis?: string;
    feedback_notes?: string;
    improvement_suggestions?: string;
  }, token: string) => {
    return api.post(`/api/ai-cases/feedback/${caseId}`, feedbackData, buildHeaders({ token }));
  },

  /**
   * Submit AI Suggestion
   * 
   * Purpose: Submit physician suggestions for AI findings
   * 
   * @param suggestionData - Suggestion data including patient ID, type, title, text, etc.
   * @param token - Authentication token
   * @returns Promise with suggestion submission result
   */
  submitAISuggestion: (suggestionData: {
    patid: string;
    suggestion_type: string;
    suggestion_title: string;
    suggestion_text: string;
    confidence_score: number;
    priority_level: string;
    category: string;
    related_findings: Record<string, string>;
    evidence_sources: string[];
    contraindications: string;
    cost_estimate: number;
    time_estimate: string;
    expires_at: string | null;
    tags: string[];
    ai_model_version: string;
  }, token: string) => {
    return api.post('/api/ai-cases/suggestions', suggestionData, buildHeaders({ token }));
  },

  /**
   * Get AI Suggestions
   * 
   * Purpose: Fetch AI suggestions for a specific case or all suggestions
   * 
   * @param token - Authentication token
   * @param params - Optional query parameters
   * @returns Promise with suggestions data
   */
  getAISuggestions: (token: string, params?: {
    caseId?: string;
    patientId?: string;
    suggestionType?: string;
    priority?: string;
    status?: string;
    page?: number;
    limit?: number;
  }) => {
    const queryParams = params ? { ...params } : {};
    return api.get('/api/ai-cases/suggestions', queryParams, buildHeaders({ token }));
  },

  /**
   * Update AI Suggestion
   * 
   * Purpose: Update an existing AI suggestion
   * 
   * @param suggestionId - Suggestion ID to update
   * @param updateData - Updated suggestion data
   * @param token - Authentication token
   * @returns Promise with updated suggestion data
   */
  updateAISuggestion: (suggestionId: string, updateData: {
    suggestion_title?: string;
    suggestion_text?: string;
    priority_level?: string;
    category?: string;
    related_findings?: Record<string, string>;
    evidence_sources?: string[];
    contraindications?: string;
    cost_estimate?: number;
    time_estimate?: string;
    expires_at?: string | null;
    tags?: string[];
  }, token: string) => {
    return api.put(`/api/ai-cases/suggestions/${suggestionId}`, updateData, buildHeaders({ token }));
  },

  /**
   * Delete AI Suggestion
   * 
   * Purpose: Delete an AI suggestion
   * 
   * @param suggestionId - Suggestion ID to delete
   * @param token - Authentication token
   * @returns Promise with deletion result
   */
  deleteAISuggestion: (suggestionId: string, token: string) => {
    return api.delete(`/api/ai-cases/suggestions/${suggestionId}`, {}, buildHeaders({ token }));
  },

  /**
   * Get Suggestion Statistics
   * 
   * Purpose: Fetch statistics about AI suggestions
   * 
   * @param token - Authentication token
   * @param timeRange - Optional time range filter
   * @returns Promise with suggestion statistics
   */
  getSuggestionStats: (token: string, timeRange?: 'today' | 'week' | 'month') => {
    const params = timeRange ? { timeRange } : {};
    return api.get('/api/ai-cases/suggestions/statistics', params, buildHeaders({ token }));
  }
};

/*
 * End of File: aiPredictionAPI.ts
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */
