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

// Use REACT_APP_API_BASE_URL instead of REACT_APP_API_URL
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:8080'; // Default to localhost if not set

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

// Request interceptor
api.interceptors.request.use((config) => {
  const token = getToken();
  console.log('[API] Current token:', token);
  console.log('[API] Making request to:', config.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);
});

// Response interceptor
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');
      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) => {
    try {
      const response = await api.post('/sureserve/sequence/seq', data);
      return response.data;
    } catch (error) {
      console.error('[API] Error creating sequence:', error);
      throw error;
    }
  },

  update: async (id, data) => {
    try {
      const response = await api.put(`/sureserve/sequence/seq/${id}`, data);
      return response.data;
    } catch (error) {
      console.error(`[API] Error updating sequence ${id}:`, error);
      throw error;
    }
  },

  delete: async (id) => {
    try {
      const response = await api.delete(`/sureserve/sequence/seq/${id}`);
      return response.data;
    } catch (error) {
      console.error(`[API] Error deleting sequence ${id}:`, error);
      throw error;
    }
  },
};

export default SequenceGeneratorAPI;