import axios from 'axios';
 import { getToken } from '../../src/utils/tokenService'; 

const BASE_URL = process.env.REACT_APP_API_URL;

// Fetch token from localStorage
//  getToken = () => localStorage.getItem('token');

// Create an Axios instance
const apiClient = axios.create({
  baseURL: BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  
});

// Add a request interceptor to include Authorization header
apiClient.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      console.log("token: ",token);
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Generic error handler function
const handleError = (error) => {
  let errorMessage = 'An unknown error occurred';
  console.error('Error Details:', error);

  if (error.response) {
    // HTTP errors
    switch (error.response.status) {
      case 401:
        errorMessage = 'Unauthorized - Please login again.';
        break;
      case 403:
        errorMessage = 'Forbidden - Access denied.';
        break;
      case 404:
        errorMessage = 'Service not found.';
        break;
      case 408:
        errorMessage = 'Request timed out.';
        break;
      case 500:
        errorMessage = 'Internal server error.';
        break;
      default:
        errorMessage = `Unexpected error: ${error.response.statusText || 'Server Error'}`;
    }
  } else if (error.request) {
    // No response received
    errorMessage = 'No response from server. Please check your connection.';
  } else {
    // Other errors
    errorMessage = error.message || 'An unexpected error occurred.';
  }

  return Promise.reject(errorMessage); // Return error message as rejected promise
};

// Define the reusable methods
// const apiService = {
//   get: (url, params) =>
//     apiClient
//       .get(url, { params: params || {} })
//       .catch(handleError), // Attach error handler
//   post: (url, body = {}) =>
//     apiClient
//       .post(url, body)
//       .catch(handleError), // Attach error handler
//   put: (url, body = {}) =>
//     apiClient
//       .put(url, body)
//       .catch(handleError), // Attach error handler
//   delete: (url) =>
//     apiClient
//       .delete(url)
//       .catch(handleError), // Attach error handler
// };

const apiService = {
  get: (url, params) =>
    apiClient
      .get(url, { params: params || {} })
      .catch(handleError), // Attach error handler

  post: (url, body = {}, options = {}) =>
    apiClient
      .post(url, body, options) // Pass options such as headers
      .catch(handleError), // Attach error handler

  put: (url, body = {}, options = {}) =>
    apiClient
      .put(url, body, options) // Pass options such as headers
      .catch(handleError), // Attach error handler

  delete: (url, options = {}) =>
    apiClient
      .delete(url, options) // Pass options such as headers
      .catch(handleError), // Attach error handler
};
// Add at the bottom of APIService.js

export const getSubmenuItems = async (id) => {
  const response = await apiService.get(`/api1/submenu1/${id}`);
  return response.data; 
};
export const addSubmenuItem = async (menuId, submenuData) => {
  const response = await apiService.post(`/api1/menu/${menuId}/submenu`, submenuData);
  return response.data;
};
export const updateMenuItem = (id, formData) => apiService.put(`/api1/submenu1/${id}`, formData);
export const deleteMenuItem = (id) => apiService.delete(`/api1/menu/${id}`);


export default apiService;
