import { create } from 'apisauce';
import { store } from '@/store/store';
import { selectAccessToken ,selectRefreshToken } from '@/modules/auth/store/selectors';
import { refreshToken, logout } from '@/modules/auth/store/authSlice';
import { clearSelectedService } from '@/modules/integrations/store/integrationsSlice';

// Store for pending requests that need to be retried
let pendingRequest: any = null;

const http = create({
  // baseURL: 'http://192.168.1.17:4000',
  // baseURL: 'http://160.187.167.216',
  baseURL: 'https://81243590fe4c.ngrok-free.app',
  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);
  const refreshToken=selectRefreshToken(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(async (response) => {
  if (response.status === 401) {
    console.warn('Unauthorized request - token may be expired');
    
    // Skip refresh token logic for auth endpoints to avoid infinite loops
    const authEndpoints = [
      '/api/v1/auth/login',
      '/api/v1/auth/refresh',
      '/api/v1/users/register',
      '/api/v1/users/signup',
    ];
    
    const isAuthEndpoint = authEndpoints.some(endpoint => 
      response.config?.url?.startsWith(endpoint)
    );
    
    if (isAuthEndpoint) {
      return; // Skip refresh token logic for auth endpoints
    }
    
    // Store the original request for retry
    pendingRequest = {
      method: response.config?.method?.toUpperCase(),
      url: response.config?.url,
      data: response.config?.data,
      params: response.config?.params,
      headers: response.config?.headers,
    };
    
    // Get refresh token from store
    const state = store.getState();
    const refreshTokenValue = selectRefreshToken(state);
    
    if (!refreshTokenValue) {
      console.warn('No refresh token available - logging out');
      store.dispatch(logout());
      store.dispatch(clearSelectedService());
      return;
    }
    
    try {
      // Attempt to refresh the token
      console.log('Attempting to refresh token...');
      const refreshResult = await store.dispatch(refreshToken(refreshTokenValue));
      
      if (refreshToken.fulfilled.match(refreshResult)) {
        console.log('Token refreshed successfully - retrying original request');
        
        // Retry the original request with new token
        if (pendingRequest) {
          try {
            const newState = store.getState();
            const newToken = selectAccessToken(newState);
            
            if (newToken) {
              // Prepare headers with new token
              const retryHeaders = {
                ...pendingRequest.headers,
                Authorization: `Bearer ${newToken}`,
              };
              
              // Retry the request
              let retryResponse;
              switch (pendingRequest.method) {
                case 'GET':
                  retryResponse = await http.get(pendingRequest.url, pendingRequest.params, {
                    headers: retryHeaders,
                  });
                  break;
                case 'POST':
                  retryResponse = await http.post(pendingRequest.url, pendingRequest.data, {
                    headers: retryHeaders,
                  });
                  break;
                case 'PUT':
                  retryResponse = await http.put(pendingRequest.url, pendingRequest.data, {
                    headers: retryHeaders,
                  });
                  break;
                case 'DELETE':
                  retryResponse = await http.delete(pendingRequest.url, pendingRequest.params, {
                    headers: retryHeaders,
                  });
                  break;
                case 'PATCH':
                  retryResponse = await http.patch(pendingRequest.url, pendingRequest.data, {
                    headers: retryHeaders,
                  });
                  break;
                default:
                  console.warn('Unsupported HTTP method for retry:', pendingRequest.method);
                  return;
              }
              
              console.log('Original request retried successfully:', retryResponse);
              
              // Update the original response with retry response data
              if (retryResponse) {
                response.data = retryResponse.data;
                response.status = retryResponse.status;
                response.ok = retryResponse.ok;
                response.problem = retryResponse.problem;
              }
            }
          } catch (retryError) {
            console.error('Error retrying original request:', retryError);
          } finally {
            // Clear pending request
            pendingRequest = null;
          }
        }
      } else {
        console.warn('Token refresh failed - logging out');
        store.dispatch(logout());
        store.dispatch(clearSelectedService());
        pendingRequest = null;
      }
    } catch (error) {
      console.error('Error during token refresh:', error);
      store.dispatch(logout());
      store.dispatch(clearSelectedService());
      pendingRequest = null;
    }
  }
  
  // Log successful requests for debugging (optional)
  if (response.ok && __DEV__) {
    // console.log(`✅ API Success: ${response.config?.method?.toUpperCase()} ${response.config?.url}`);
  }
});

export default http;


