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

const API_BASE_URL = process.env.REACT_APP_API_URL || '';

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json'
  }
});

// Add request interceptor to attach token
api.interceptors.request.use((config) => {
  // Always get fresh token for each request
  const token = getToken();
  console.log('[API] Current token:', token); // Log the token
  console.log('[API] Making request to:', config.url); // Log the request URL
  
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  } else {
    console.warn('No authToken found for request!');
  }
  
  return config;
}, (error) => {
  console.error('[API] Request error:', error);
  return Promise.reject(error);
});

// ... rest of the interceptors and API methods remain the same ...

// Add response interceptor to log responses
api.interceptors.response.use((response) => {
  console.log('[API] Response received:', {
    status: response.status,
    url: response.config.url,
    data: response.data
  });
  return response;
}, (error) => {
  console.error('[API] Response error:', {
    status: error.response?.status,
    url: error.config?.url,
    message: error.message,
    response: error.response?.data
  });
  return Promise.reject(error);
});

const SequenceGeneratorAPI = {
  getAll: async () => {
    try {
      console.log('[API] Fetching all sequences'); // Additional log
      const response = await api.get('/sureserve/sequence/seq');
      return response.data;
    } catch (error) {
      console.error('[API] Error fetching sequences:', error);
      throw error;
    }
  },

  getById: async (id) => {
    try {
      console.log(`[API] Fetching sequence with ID: ${id}`);
      const response = await api.get(`/sureserve/sequence/seq/${id}`);
      return response.data;
    } catch (error) {
      console.error(`[API] Error fetching sequence ${id}:`, error);
      throw error;
    }
  },

  create: async (data) => api.post('/sureserve/sequence/seq', data), // ✅ Make sure this exists
  update: async (id, data) => api.put(`/sureserve/sequence/seq/${id}`, data),
  delete: async (id) => api.delete(`/sureserve/sequence/seq/${id}`),
};

export default SequenceGeneratorAPI;