/**
 * API Service Layer
 * 
 * Axios instance with WordPress nonce authentication
 */

import axios, { AxiosInstance } from 'axios';

// Development mode check (Vite sets import.meta.env)
const isDev = import.meta.env.DEV;

// Create Axios instance
export const api: AxiosInstance = axios.create({
  baseURL: window.varihuConfig.restUrl,
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': window.varihuConfig.nonce,
  },
  timeout: 30000, // 30 seconds
});

// Request interceptor (logging)
api.interceptors.request.use(
  (config) => {
    if (isDev) {
      console.log(`[API] ${config.method?.toUpperCase()} ${config.url}`, config.data);
    }
    return config;
  },
  (error) => {
    console.error('[API] Request error:', error);
    return Promise.reject(error);
  }
);

// Response interceptor (error handling + nonce refresh)
api.interceptors.response.use(
  (response) => {
    if (isDev) {
      console.log(`[API] Response:`, response.data);
    }
    return response;
  },
  async (error) => {
    console.error('[API] Response error:', error.response?.data || error.message);
    
    // Handle specific error codes
    if (error.response?.status === 401) {
      console.error('[API] Authentication failed - nonce expired?');
    } else if (error.response?.status === 403) {
      // ✅ SECURITY FIX: Auto-refresh nonce on 403 error
      if (error.config && !error.config._retry) {
        error.config._retry = true;
        
        try {
          console.log('[API] Attempting nonce refresh...');
          
          // Fetch new nonce from WordPress (use dynamic ajaxUrl from config)
          const response = await fetch(`${window.varihuConfig.ajaxUrl}?action=varihu_refresh_nonce`, {
            credentials: 'same-origin'
          });
          
          if (!response.ok) {
            throw new Error('Nonce refresh failed');
          }
          
          const data = await response.json();
          
          if (data.success && data.data.nonce) {
            // Update global nonce
            window.varihuConfig.nonce = data.data.nonce;
            api.defaults.headers['X-WP-Nonce'] = data.data.nonce;
            
            // Retry failed request with new nonce
            error.config.headers['X-WP-Nonce'] = data.data.nonce;
            
            console.log('[API] Nonce refreshed successfully, retrying request...');
            return api.request(error.config);
          }
        } catch (refreshError) {
          console.error('[API] Nonce refresh failed:', refreshError);
          // Redirect to login if refresh fails
          window.location.href = '/wp-admin/admin.php?page=variation-hub';
          return Promise.reject(error);
        }
      }
      
      console.error('[API] Permission denied');
    } else if (error.response?.status >= 500) {
      console.error('[API] Server error');
    }
    
    return Promise.reject(error);
  }
);

// Export API methods
export { 
  getVariations, 
  getVariation, 
  updateVariation,
  getVariationsByIds,
  getProduct
} from './variations';

export {
  getLicenseInfo,
  activateLicense,
  deactivateLicense,
  checkFeature
} from './license';

export default api;
