import { create } from 'apisauce';
import { store } from '@/store/store';
import { selectAccessToken } from '@/modules/auth/store/selectors';

const http = create({
  baseURL: 'http://192.168.1.12:4000',
  // baseURL: 'http://160.187.167.216',
  timeout: 10000,
});

// Add request interceptor to include auth token
http.addRequestTransform((request) => {
  // Skip adding token for authentication and public endpoints
  const publicEndpoints = [
    '/api/v1/auth/login',           // All auth endpoints
    '/api/v1/users/register',  // User registration
    '/api/v1/users/signup',    // User signup
    '/api/v1/public/',         // Any public endpoints
  ];
  
  const isPublicEndpoint = publicEndpoints.some(endpoint => 
    request.url?.startsWith(endpoint)
  );
  
  if (isPublicEndpoint) {
    return; // Skip adding token for public endpoints
  }
  
  const state = store.getState();
  const token = selectAccessToken(state);
  
  if (token) {
    request.headers = {
      ...request.headers,
      Authorization: `Bearer ${token}`,
    };
  } else {
    console.warn('No access token found for API request to:', request.url);
  }
});

// Add response interceptor for error handling
http.addResponseTransform((response) => {
  if (response.status === 401) {
    console.warn('Unauthorized request - token may be expired');
    // You could dispatch a logout action here if needed
    // dispatch(logout());
  }
  
  // Log successful requests for debugging (optional)
  if (response.ok && __DEV__) {
    console.log(`✅ API Success: ${response.config?.method?.toUpperCase()} ${response.config?.url}`);
  }
});

export default http;


