// ================================================================
// frontend/src/api/services/forecasting.ts
// ================================================================
/**
 * Forecasting Service - Complete backend alignment
 *
 * Backend API structure (3-tier architecture):
 * - ATOMIC: forecasts.py
 * - OPERATIONS: forecasting_operations.py
 * - ANALYTICS: analytics.py
 *
 * Last Updated: 2025-10-05
 * Status: ✅ Complete - Zero drift with backend
 */

import { apiClient } from '../client/apiClient';
import {
  ForecastRequest,
  ForecastResponse,
  BatchForecastRequest,
  BatchForecastResponse,
  ForecastListResponse,
  ForecastByIdResponse,
  ForecastStatistics,
  DeleteForecastResponse,
  GetForecastsParams,
  ForecastingHealthResponse,
  MultiDayForecastResponse,
  ScenarioSimulationRequest,
  ScenarioSimulationResponse,
  ScenarioComparisonRequest,
  ScenarioComparisonResponse,
} from '../types/forecasting';

export class ForecastingService {
  private readonly baseUrl = '/tenants';

  // ===================================================================
  // ATOMIC: Forecast CRUD
  // Backend: services/forecasting/app/api/forecasts.py
  // ===================================================================

  /**
   * List forecasts with optional filters
   * GET /tenants/{tenant_id}/forecasting/forecasts
   */
  async getTenantForecasts(
    tenantId: string,
    params?: GetForecastsParams
  ): Promise<ForecastListResponse> {
    const searchParams = new URLSearchParams();

    if (params?.inventory_product_id) {
      searchParams.append('inventory_product_id', params.inventory_product_id);
    }
    if (params?.start_date) {
      searchParams.append('start_date', params.start_date);
    }
    if (params?.end_date) {
      searchParams.append('end_date', params.end_date);
    }
    if (params?.skip !== undefined) {
      searchParams.append('skip', params.skip.toString());
    }
    if (params?.limit !== undefined) {
      searchParams.append('limit', params.limit.toString());
    }

    const queryString = searchParams.toString();
    const url = `${this.baseUrl}/${tenantId}/forecasting/forecasts${queryString ? `?${queryString}` : ''}`;

    return apiClient.get<ForecastListResponse>(url);
  }

  /**
   * Get specific forecast by ID
   * GET /tenants/{tenant_id}/forecasting/forecasts/{forecast_id}
   */
  async getForecastById(
    tenantId: string,
    forecastId: string
  ): Promise<ForecastByIdResponse> {
    return apiClient.get<ForecastByIdResponse>(
      `${this.baseUrl}/${tenantId}/forecasting/forecasts/${forecastId}`
    );
  }

  /**
   * Delete a forecast
   * DELETE /tenants/{tenant_id}/forecasting/forecasts/{forecast_id}
   */
  async deleteForecast(
    tenantId: string,
    forecastId: string
  ): Promise<DeleteForecastResponse> {
    return apiClient.delete<DeleteForecastResponse>(
      `${this.baseUrl}/${tenantId}/forecasting/forecasts/${forecastId}`
    );
  }

  // ===================================================================
  // OPERATIONS: Forecasting Operations
  // Backend: services/forecasting/app/api/forecasting_operations.py
  // ===================================================================

  /**
   * Generate a single product forecast
   * POST /tenants/{tenant_id}/forecasting/operations/single
   */
  async createSingleForecast(
    tenantId: string,
    request: ForecastRequest
  ): Promise<ForecastResponse> {
    return apiClient.post<ForecastResponse, ForecastRequest>(
      `${this.baseUrl}/${tenantId}/forecasting/operations/single`,
      request
    );
  }

  /**
   * Generate multiple daily forecasts for the specified period
   * POST /tenants/{tenant_id}/forecasting/operations/multi-day
   */
  async createMultiDayForecast(
    tenantId: string,
    request: ForecastRequest
  ): Promise<MultiDayForecastResponse> {
    return apiClient.post<MultiDayForecastResponse, ForecastRequest>(
      `${this.baseUrl}/${tenantId}/forecasting/operations/multi-day`,
      request
    );
  }

  /**
   * Generate batch forecasts for multiple products
   * POST /tenants/{tenant_id}/forecasting/operations/batch
   */
  async createBatchForecast(
    tenantId: string,
    request: BatchForecastRequest
  ): Promise<BatchForecastResponse> {
    return apiClient.post<BatchForecastResponse, BatchForecastRequest>(
      `${this.baseUrl}/${tenantId}/forecasting/operations/batch`,
      request
    );
  }

  /**
   * Get comprehensive forecast statistics
   * GET /tenants/{tenant_id}/forecasting/operations/statistics
   */
  async getForecastStatistics(
    tenantId: string
  ): Promise<ForecastStatistics> {
    return apiClient.get<ForecastStatistics>(
      `${this.baseUrl}/${tenantId}/forecasting/operations/statistics`
    );
  }

  /**
   * Generate real-time prediction
   * POST /tenants/{tenant_id}/forecasting/operations/realtime
   */
  async generateRealtimePrediction(
    tenantId: string,
    predictionRequest: {
      inventory_product_id: string;
      model_id: string;
      features: Record<string, any>;
      model_path?: string;
      confidence_level?: number;
    }
  ): Promise<{
    tenant_id: string;
    inventory_product_id: string;
    model_id: string;
    prediction: number;
    confidence: number;
    timestamp: string;
  }> {
    return apiClient.post(
      `${this.baseUrl}/${tenantId}/forecasting/operations/realtime`,
      predictionRequest
    );
  }

  /**
   * Generate batch predictions
   * POST /tenants/{tenant_id}/forecasting/operations/batch-predictions
   */
  async generateBatchPredictions(
    tenantId: string,
    predictionsRequest: Array<{
      inventory_product_id?: string;
      model_id: string;
      features: Record<string, any>;
      model_path?: string;
      confidence_level?: number;
    }>
  ): Promise<{
    predictions: Array<{
      inventory_product_id?: string;
      prediction?: number;
      confidence?: number;
      success: boolean;
      error?: string;
    }>;
    total: number;
  }> {
    return apiClient.post(
      `${this.baseUrl}/${tenantId}/forecasting/operations/batch-predictions`,
      predictionsRequest
    );
  }

  /**
   * Validate predictions against actual sales data
   * POST /tenants/{tenant_id}/forecasting/operations/validate-predictions
   */
  async validatePredictions(
    tenantId: string,
    startDate: string,
    endDate: string
  ): Promise<any> {
    return apiClient.post(
      `${this.baseUrl}/${tenantId}/forecasting/operations/validate-predictions?start_date=${startDate}&end_date=${endDate}`,
      {}
    );
  }

  /**
   * Clear prediction cache
   * DELETE /tenants/{tenant_id}/forecasting/operations/cache
   */
  async clearPredictionCache(tenantId: string): Promise<{ message: string }> {
    return apiClient.delete(
      `${this.baseUrl}/${tenantId}/forecasting/operations/cache`
    );
  }

  // ===================================================================
  // ANALYTICS: Performance Metrics
  // Backend: services/forecasting/app/api/analytics.py
  // ===================================================================

  /**
   * Get predictions performance analytics
   * GET /tenants/{tenant_id}/forecasting/analytics/predictions-performance
   */
  async getPredictionsPerformance(
    tenantId: string,
    startDate?: string,
    endDate?: string
  ): Promise<any> {
    const searchParams = new URLSearchParams();
    if (startDate) searchParams.append('start_date', startDate);
    if (endDate) searchParams.append('end_date', endDate);

    const queryString = searchParams.toString();
    return apiClient.get(
      `${this.baseUrl}/${tenantId}/forecasting/analytics/predictions-performance${queryString ? `?${queryString}` : ''}`
    );
  }

  // ===================================================================
  // SCENARIO SIMULATION - PROFESSIONAL/ENTERPRISE ONLY
  // Backend: services/forecasting/app/api/scenario_operations.py
  // ===================================================================

  /**
   * Run a "what-if" scenario simulation on forecasts
   * POST /tenants/{tenant_id}/forecasting/analytics/scenario-simulation
   *
   * **PROFESSIONAL/ENTERPRISE ONLY**
   */
  async simulateScenario(
    tenantId: string,
    request: ScenarioSimulationRequest
  ): Promise<ScenarioSimulationResponse> {
    return apiClient.post<ScenarioSimulationResponse, ScenarioSimulationRequest>(
      `${this.baseUrl}/${tenantId}/forecasting/analytics/scenario-simulation`,
      request
    );
  }

  /**
   * Compare multiple scenario simulations
   * POST /tenants/{tenant_id}/forecasting/analytics/scenario-comparison
   *
   * **PROFESSIONAL/ENTERPRISE ONLY**
   */
  async compareScenarios(
    tenantId: string,
    request: ScenarioComparisonRequest
  ): Promise<ScenarioComparisonResponse> {
    return apiClient.post<ScenarioComparisonResponse, ScenarioComparisonRequest>(
      `${this.baseUrl}/${tenantId}/forecasting/analytics/scenario-comparison`,
      request
    );
  }

  // ===================================================================
  // Health Check
  // ===================================================================

  /**
   * Health check for forecasting service
   * GET /health
   */
  async getHealthCheck(): Promise<ForecastingHealthResponse> {
    return apiClient.get<ForecastingHealthResponse>('/health');
  }
}

// Export singleton instance
export const forecastingService = new ForecastingService();
export default forecastingService;
