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

// Create axios instance with base configuration
const apiClient = axios.create({
  baseURL: process.env.REACT_APP_API_URL || 'http://157.66.191.31:33730/back/',
});

// Add request interceptor to inject token
apiClient.interceptors.request.use((config) => {
  const token = getToken();
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

// Response interceptor for error handling
apiClient.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response) {
      // Handle specific status codes
      if (error.response.status === 401) {
        // Handle unauthorized (token expired)
        console.error('Authentication failed');
      }
      throw new Error(error.response.data.message || 'Request failed');
    }
    throw new Error(error.message || 'Network error');
  }
);

export const fetchAllTokens = async () => {
  try {
    return await apiClient.get('apiregistery/getall');
  } catch (error) {
    console.error('Fetch tokens error:', error);
    throw error;
  }
};

export const generateToken = async (token_name) => {
  try {
    return await apiClient.post(
      'apiregistery/generateToken',
      new URLSearchParams({ token_name }),
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
    );
  } catch (error) {
    console.error('Generate token error:', error);
    throw error;
  }
};

export const createToken = async (tokenData) => {
  try {
    return await apiClient.post('apiregistery/create', tokenData);
  } catch (error) {
    console.error('Create token error:', error);
    throw error;
  }
};

export const updateToken = async (id, tokenData) => {
  try {
    return await apiClient.put(`apiregistery/update/${id}`, tokenData);
  } catch (error) {
    console.error('Update token error:', error);
    throw error;
  }
};

export const deleteToken = async (id) => {
  try {
    return await apiClient.delete(`apiregistery/delete/${id}`);
  } catch (error) {
    console.error('Delete token error:', error);
    throw error;
  }
};