import { API_BASE_URL, API_ENDPOINTS } from "../config/api";

export interface Recommendation {
  id: string;
  userId: string;
  fitnessProfileId: string;
  recommendationText: string;
  activityPlan: string;
  dietPlan: string;
  status: "pending" | "approved" | "rejected";
  generatedAt: string;
  approvedAt?: string | null;
  approvedBy?: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface GenerateRecommendationRequest {
  userId: string;
  useExternalModel?: boolean;
  modelProvider?: "openai" | "deepseek" | "ollama";
}

/**
 * Get recommendations for a user
 *
 * @param userId - Clerk user ID
 * @param token - Auth token
 * @returns Array of recommendations
 */
export async function getRecommendations(
  userId: string,
  token: string | null,
): Promise<Recommendation[]> {
  const headers: any = {
    "Content-Type": "application/json",
  };

  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }

  const response = await fetch(
    `${API_BASE_URL}${API_ENDPOINTS.RECOMMENDATIONS}?userId=${userId}`,
    { headers },
  );

  if (!response.ok) {
    throw new Error(`Failed to fetch recommendations: ${response.status}`);
  }

  const result = await response.json();

  // Handle standardized API response format
  // API returns: { success: true, data: [...], meta: {...} }
  if (result.success && result.data) {
    return Array.isArray(result.data) ? result.data : [];
  }

  // Fallback for legacy format (direct array)
  return Array.isArray(result) ? result : [];
}

/**
 * Generate a new AI recommendation for a user
 *
 * @param data - Generation request data
 * @param token - Auth token
 * @returns The generated recommendation
 */
export async function generateRecommendation(
  data: GenerateRecommendationRequest,
  token: string | null,
): Promise<Recommendation> {
  const headers: any = {
    "Content-Type": "application/json",
  };

  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }

  const response = await fetch(
    `${API_BASE_URL}${API_ENDPOINTS.RECOMMENDATIONS}/generate`,
    {
      method: "POST",
      headers,
      body: JSON.stringify(data),
    },
  );

  if (!response.ok) {
    throw new Error(`Failed to generate recommendation: ${response.status}`);
  }

  const result = await response.json();

  // Handle standardized API response format
  if (result.success && result.data) {
    return result.data;
  }

  // Fallback for legacy format
  return result;
}

/**
 * Approve a recommendation (admin/trainer only)
 *
 * @param recommendationId - Recommendation ID
 * @param token - Auth token
 * @param approvedBy - User ID of the approver (optional)
 * @returns The approved recommendation
 */
export async function approveRecommendation(
  recommendationId: string,
  token: string | null,
  approvedBy?: string,
): Promise<Recommendation> {
  const headers: any = {
    "Content-Type": "application/json",
  };

  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }

  const response = await fetch(
    `${API_BASE_URL}${API_ENDPOINTS.RECOMMENDATIONS}/approve`,
    {
      method: "POST",
      headers,
      body: JSON.stringify({
        recommendationId,
        status: "approved",
        approvedBy,
      }),
    },
  );

  if (!response.ok) {
    throw new Error(`Failed to approve recommendation: ${response.status}`);
  }

  const result = await response.json();

  // Handle standardized API response format
  if (result.success && result.data) {
    return result.data;
  }

  // Fallback for legacy format
  return result;
}
