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

const USERS_LOGIN_ENDPOINT = `${API_BASE_URL}/users/login`;
const USERS_LOGOUT_ENDPOINT = `${API_BASE_URL}/users/logout`;
const USERS_ME_ENDPOINT = `${API_BASE_URL}/users/me`;

/**
 * Initiates the OIDC login flow.
 */
export const login = () => {
  const frontendCallbackUri = window.location.origin;
  const loginUrl = `${USERS_LOGIN_ENDPOINT}?frontend_callback_uri=${encodeURIComponent(frontendCallbackUri)}`;
  window.location.href = loginUrl;
};

/**
 * Performs local email/password login.
 */
export const loginLocal = async (email, password) => {
  const response = await fetch(`${USERS_LOGIN_ENDPOINT}/local`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password }),
  });
  if (!response.ok) {
    const err = await response.json().catch(() => ({ detail: "Login failed" }));
    throw new Error(err.detail || `Login failed. Status: ${response.status}`);
  }
  return await response.json();
};

/**
 * Fetches authentication configuration.
 */
export const getAuthConfig = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/users/config`, {
      method: "GET"
    });
    if (!response.ok) return { oidc_configured: false, allow_password_login: true };
    const data = await response.json();
    return { 
      oidc_configured: data.oidc_configured,
      allow_password_login: data.allow_password_login 
    };
  } catch (err) {
    console.error("Failed to fetch auth config", err);
    return { oidc_configured: false, allow_password_login: true };
  }
};

/**
 * Fetches the current user's status.
 */
export const getUserStatus = async (userId) => {
  return await fetchWithAuth('/users/me', { method: 'GET', headers: { 'X-User-ID': userId } });
};

/**
 * Logs the current user out.
 */
export const logout = async () => {
  return await fetchWithAuth('/users/logout', { method: 'POST' });
};

/**
 * Updates the user's local password.
 */
export const updatePassword = async (current_password, new_password) => {
  return await fetchWithAuth('/users/password', {
    method: 'PUT',
    body: { current_password, new_password }
  });
};

/**
 * Fetches the user profile info.
 */
export const getUserProfile = async () => {
  return await fetchWithAuth('/users/me/profile', { method: 'GET' });
};

/**
 * Updates the user profile info.
 */
export const updateUserProfile = async (profileData) => {
  return await fetchWithAuth('/users/me/profile', { 
    method: 'PUT', 
    body: profileData 
  });
};

/**
 * Fetches the current user's preferences.
 */
export const getUserConfig = async () => {
  return await fetchWithAuth('/users/me/config');
};

/**
 * Updates the current user's preferences.
 */
export const updateUserConfig = async (config) => {
  return await fetchWithAuth('/users/me/config', { 
    method: 'PUT', 
    body: config 
  });
};

/**
 * Download the effective user configurations as YAML.
 */
export const exportUserConfig = async () => {
  return await fetchWithAuth('/users/me/config/export', { method: 'GET', raw: true });
};

/**
 * Import user configuration via multipart form.
 */
export const importUserConfig = async (formData) => {
  return await fetchWithAuth('/users/me/config/import', { 
    method: 'POST', 
    body: formData 
  });
};
