import client from './client';
import { API_ENDPOINTS } from './ApiSources';
import { getFingerprint } from './fingerprint';


/**
 * New user registration
 * @param {Object} userData - User data
 * @param {string} userData.username - Username
 * @param {string} userData.password - Password
 * @param {string} userData.email - Email (optional)
 * @returns {Promise<Object>} Registered user data
 */
export const signup = async (userData) => {
    try {
      const response = await client.post(API_ENDPOINTS.AUTH.REGISTER, userData);
      return response.data;
    } catch (error) {
      throw error.response?.data || error.message;
    }
};

/**
 * Get current user information
 * @returns {Promise<Object>} Current user information
 */
export const getMe = async () => {
    try {
      const response = await client.get(API_ENDPOINTS.AUTH.ME);
      return response.data;
    } catch (error) {
      throw error.response?.data || error.message;
    }
  };

/**
 * User logout
 * Backend automatically removes refresh token from httpOnly cookie
 * @returns {Promise<Object>} Logout result
 */
export const logout = async () => {
  try {
    const response = await client.post(API_ENDPOINTS.AUTH.LOGOUT);
    if (response.data.status_code === 200) {
      localStorage.removeItem('access_token');
      localStorage.removeItem('fingerprint');
    }
    return response.data;
  } catch (error) {
    localStorage.removeItem('access_token');
    localStorage.removeItem('fingerprint');
    throw error.response?.data || error.message;
  }
};

/**
 * User login
 * @param {string} username - Username
 * @param {string} password - Password
 * @returns {Promise<Object>} Login result
 */
export const login = async (username, password) => {
  try {
    const fingerprint = await getFingerprint();
    const formData = new FormData();
    formData.append('username', username);
    formData.append('password', password);
    formData.append('fingerprint', fingerprint);
    const response = await client.post(API_ENDPOINTS.AUTH.LOGIN, formData,
      {
        headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    console.log(response.data);
    if (response.data.access_token && response.data.token_type === 'bearer') {
      localStorage.setItem('access_token', response.data.access_token); 
    }
    return response.data;
  } catch (error) {
    throw error.response?.data || error.message;
  }
};
