import { apiClient } from '@/services/api/client';
import { parseApiError } from '@/utils/apiErrorHandler';

/**
 * Service pour l'adaptation de bitrate
 * T0350: Create Bitrate Adaptation Frontend Service
 */

/**
 * Interface pour la requête d'adaptation de bitrate
 */
export interface AdaptBitrateRequest {
  current_bitrate: number;
  bandwidth: number;
  buffer_level: number;
}

/**
 * Interface pour la réponse d'adaptation de bitrate
 */
export interface AdaptBitrateResponse {
  recommended_bitrate: number;
}

/**
 * Interface pour les analytics d'adaptation de bitrate
 * T0354: Create Bitrate Adaptation Analytics Endpoint
 */
export interface BitrateAnalytics {
  total_adaptations: number;
  reasons: Record<string, number>;
  adaptations_over_time: AdaptationTimePoint[];
  average_bandwidth?: number;
}

/**
 * Interface pour un point temporel d'adaptation
 */
export interface AdaptationTimePoint {
  date: string;
  count: number;
}

/**
 * Adapte le bitrate en fonction des métriques de streaming
 * @param trackId - ID du track
 * @param request - Métriques de streaming (bitrate actuel, bande passante, niveau de buffer)
 * @returns Bitrate recommandé
 * @throws Error si la requête échoue
 */
export async function adaptBitrate(
  trackId: string,
  request: AdaptBitrateRequest,
): Promise<AdaptBitrateResponse> {
  try {
    const response = await apiClient.post<AdaptBitrateResponse>(
      `/tracks/${trackId}/bitrate/adapt`,
      request,
    );
    return response.data;
  } catch (error: unknown) {
    const apiError = parseApiError(error);
    const { message } = apiError;
    const code =
      typeof apiError.code === 'string'
        ? parseInt(apiError.code, 10)
        : apiError.code;

    if (code === 401) {
      throw new Error('Unauthorized: Please log in to adapt bitrate');
    } else if (code === 400) {
      throw new Error(`Invalid request: ${message}`);
    } else if (code === 404) {
      throw new Error(`Track not found: ${trackId}`);
    } else if (code && code >= 500) {
      throw new Error(`Server error: ${message}`);
    } else if (code && code > 0) {
      throw new Error(`Request failed: ${message}`);
    } else if (message.includes('Network error')) {
      throw new Error('Network error: Unable to reach the server');
    } else {
      throw new Error(`Error: ${message}`);
    }
  }
}

/**
 * Récupère les analytics d'adaptation de bitrate pour un track
 * T0354: Create Bitrate Adaptation Analytics Endpoint
 * @param trackId - ID du track
 * @returns Analytics d'adaptation de bitrate
 * @throws Error si la requête échoue
 */
export async function getBitrateAnalytics(
  trackId: string,
): Promise<BitrateAnalytics> {
  try {
    const response = await apiClient.get<{ analytics: BitrateAnalytics }>(
      `/tracks/${trackId}/bitrate/analytics`,
    );
    return response.data.analytics;
  } catch (error: unknown) {
    const apiError = parseApiError(error);
    const { message } = apiError;
    const code =
      typeof apiError.code === 'string'
        ? parseInt(apiError.code, 10)
        : apiError.code;

    if (code === 400) {
      throw new Error(`Invalid request: ${message}`);
    } else if (code === 404) {
      throw new Error(`Track not found: ${trackId}`);
    } else if (code && code >= 500) {
      throw new Error(`Server error: ${message}`);
    } else if (code && code > 0) {
      throw new Error(`Request failed: ${message}`);
    } else if (message.includes('Network error')) {
      throw new Error('Network error: Unable to reach the server');
    } else {
      throw new Error(`Error: ${message}`);
    }
  }
}
