import axios from 'axios';
import { API_URL } from '../../../../utils/Constant';

// const API_URL = 'https://8x7r3mdp-3001.asse.devtunnels.ms';

// const login = async (EMAIL, PASSWORD) => {
//   try {
//     const response = await axios.post(`${API_URL}/login`, { EMAIL, PASSWORD });
//     return response.data.payload;
//   } catch (error) {
//     throw new Error(error.response?.data?.message || 'Login failed');
//   }
// };

const login = async (EMAIL, PASSWORD) => {
  try {
    const response = await axios.post(`${API_URL}/login`, { EMAIL, PASSWORD }, {
      withCredentials: true
    });
    const { TOKEN, refreshToken } = response.data.payload;
    localStorage.setItem('token', TOKEN);

    const config = {
        headers: {
          Authorization: TOKEN
        }
    };
    const data = await axios.get(`${API_URL}/getMe`, config);
    const profile = data.data.payload;
    localStorage.setItem('userData', JSON.stringify({username: profile.NAME_USERS, picture: profile.PICTURE}));

    return response.data.payload;
  } catch (error) {
    throw error;
  }
};

const register = async (endpoint, data) => {
  try {
    const response = await axios.post(`${API_URL}/register/${endpoint}`, data);
    return response.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || 'Registration failed');
  }
};

const forgotPassword = async (email) => {
  try {
    const response = await axios.post(`${API_URL}/forgot-password`, { email });
    return response.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || 'Password reset failed');
  }
};

const logout = () => {
  localStorage.removeItem('userData');
  localStorage.removeItem('token');
};

const validateEmail = async (TOKEN) => {
  try {
    const response = await axios.post(`${API_URL}/validateEmail`, { TOKEN });
    return response.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || 'Failed Validate');
  }
};

export default {
  login,
  register,
  forgotPassword,
  logout,
  validateEmail
};
