// API service configuration v1.4 - with auth and error interceptors
import axios from 'axios';
import { triggerGuestWarning } from '../utils/toastHandler';

export const getBaseUrl = () => {
    // Priority: Env var -> Relative path (handled by Vite proxy in dev, or Nginx/Vercel in prod)
    if (import.meta.env.VITE_API_URL) {
        return import.meta.env.VITE_API_URL;
    }
    return '/api';
};

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

let currentToken: string | null = null;
let currentOrgId: string | null = null;
let currentOrgName: string | null = null;

// Function to set the JWT token
export const setApiToken = (token: string | null) => {
    currentToken = token;
};

// Function to set the organization ID and Name (called from Layout/Context)
export const setApiOrgData = (orgId: string | null, orgName: string | null = null) => {
    currentOrgId = orgId;
    currentOrgName = orgName;
};

// Legacy support
export const setApiOrgId = (orgId: string | null) => {
    setApiOrgData(orgId, null);
};

// Alias for consistency
export const setApiOrganizationId = setApiOrgId;

// Request interceptor to add clerk user ID and Org ID headers
api.interceptors.request.use(
    (config) => {
        console.log(`[API Request] ${config.method?.toUpperCase()} ${config.url}`, {
            orgId: currentOrgId
        });
        if (currentToken) {
            config.headers['Authorization'] = `Bearer ${currentToken}`;
        }
        if (currentOrgId) {
            config.headers['x-organization-id'] = currentOrgId;
        }
        if (currentOrgName) {
            // Encode to handle special characters
            config.headers['x-organization-name'] = encodeURIComponent(currentOrgName);
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// Response interceptor to handle 403 errors (guest access denied)
api.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response?.status === 403) {
            // Check if it's a guest permission error
            const errorMessage = error.response?.data?.error || '';
            if (errorMessage.includes('Convidados') || errorMessage.includes('guest') || errorMessage.includes('permissão')) {
                triggerGuestWarning();
            }
        }
        return Promise.reject(error);
    }
);

export default api;
