import { fetchWithAuth, getUserId } from './apiClient';

/**
 * Creates a new chat session.
 */
export const createSession = async (featureName = "default", providerName = "deepseek", extraParams = {}) => {
  return await fetchWithAuth('/sessions/', {
    method: "POST",
    body: {
      feature_name: featureName,
      provider_name: providerName,
      ...extraParams
    }
  });
};

/**
 * Fetches all sessions for a specific feature for the current user.
 */
export const getUserSessions = async (featureName = "default") => {
  const params = new URLSearchParams({ feature_name: featureName, _t: Date.now() });
  return await fetchWithAuth(`/sessions/?${params.toString()}`);
};

/**
 * Updates a session's metadata.
 */
export const updateSession = async (sessionId, payload) => {
  return await fetchWithAuth(`/sessions/${sessionId}`, {
    method: "PATCH",
    body: payload
  });
};

/**
 * Gets a single chat session by ID.
 */
export const getSession = async (sessionId) => {
  return await fetchWithAuth(`/sessions/${sessionId}`);
};

/**
 * Deletes a single chat session by ID.
 */
export const deleteSession = async (sessionId) => {
  return await fetchWithAuth(`/sessions/${sessionId}`, {
    method: "DELETE"
  });
};

/**
 * Clears all chat messages for a session while preserving the session.
 */
export const clearSessionHistory = async (sessionId) => {
  return await fetchWithAuth(`/sessions/${sessionId}/clear-history`, {
    method: "POST"
  });
};

/**
 * Deletes all chat sessions for a given feature.
 */
export const deleteAllSessions = async (featureName = "default") => {
  const params = new URLSearchParams({ feature_name: featureName, _t: Date.now() });
  return await fetchWithAuth(`/sessions/?${params.toString()}`, {
    method: "DELETE"
  });
};

/**
 * Fetches the token usage status for a session.
 */
export const getSessionTokenStatus = async (sessionId) => {
  return await fetchWithAuth(`/sessions/${sessionId}/tokens`);
};

/**
 * Fetches the chat history for a session.
 */
export const getSessionMessages = async (sessionId) => {
  return await fetchWithAuth(`/sessions/${sessionId}/messages`);
};

/**
 * Requests cancellation of any running tasks for a specific session.
 */
export const cancelSession = async (sessionId) => {
  return await fetchWithAuth(`/sessions/${sessionId}/cancel`, {
    method: "POST"
  });
};

/**
 * Uploads an audio blob for a specific message.
 */
export const uploadMessageAudio = async (messageId, audioBlob) => {
  const formData = new FormData();
  formData.append("file", audioBlob, "audio.wav");

  return await fetchWithAuth(`/sessions/messages/${messageId}/audio`, {
    method: "POST",
    body: formData
  });
};

/**
 * Fetches the audio for a specific message as a blob.
 */
export const fetchMessageAudio = async (messageId) => {
  try {
    const response = await fetchWithAuth(`/sessions/messages/${messageId}/audio`, {
      method: "GET",
      raw: true
    });
    return await response.blob();
  } catch (e) {
    return null; // Silent if no audio exists
  }
};
