import axios from 'axios';
import * as SecureStore from 'expo-secure-store';
import Constants from 'expo-constants';

const BASE_URL = process.env.EXPO_PUBLIC_BACKEND_URL || 'https://dcs.n9u.net';

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

// Request interceptor to add JWT token
apiClient.interceptors.request.use(
  async (config) => {
    const token = await SecureStore.getItemAsync('jwt');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Response interceptor for handling 401
apiClient.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response?.status === 401) {
      await SecureStore.deleteItemAsync('jwt');
      // Redirect to login handled by auth context
    }
    return Promise.reject(error);
  }
);

export const api = {
  get: (path: string, config?: any) => apiClient.get(path, config),
  post: (path: string, data?: any, config?: any) => apiClient.post(path, data, config),
  put: (path: string, data?: any, config?: any) => apiClient.put(path, data, config),
  patch: (path: string, data?: any, config?: any) => apiClient.patch(path, data, config),
  delete: (path: string, config?: any) => apiClient.delete(path, config),
};

export default apiClient;
