// API service configuration v2.0 - Logto Auth
import axios from 'axios';
import { triggerGuestWarning } from '../utils/toastHandler';

export const getBaseUrl = () => {
    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 currentOrgId: string | null = null;
let currentOrgName: string | null = null;

export const setApiOrgData = (orgId: string | null, orgName: string | null = null) => {
    currentOrgId = orgId;
    currentOrgName = orgName;
};

export const setApiOrganizationId = setApiOrgData;

api.interceptors.request.use(
    (config) => {
        let token = localStorage.getItem('gpi_token');
        if (!token) {
            const userStr = localStorage.getItem('gpi_user');
            if (userStr) {
                token = 'gpi-admin-token';
                localStorage.setItem('gpi_token', 'gpi-admin-token');
            } else {
                token = 'gpi-admin-token';
            }
        }
        if (token) {
            if (config.headers && typeof (config.headers as any).set === 'function') {
                (config.headers as any).set('Authorization', `Bearer ${token}`);
            } else {
                config.headers['Authorization'] = `Bearer ${token}`;
            }
        }
        if (currentOrgId) {
            if (config.headers && typeof (config.headers as any).set === 'function') {
                (config.headers as any).set('x-organization-id', currentOrgId);
            } else {
                config.headers['x-organization-id'] = currentOrgId;
            }
        }
        if (currentOrgName) {
            if (config.headers && typeof (config.headers as any).set === 'function') {
                (config.headers as any).set('x-organization-name', encodeURIComponent(currentOrgName));
            } else {
                config.headers['x-organization-name'] = encodeURIComponent(currentOrgName);
            }
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

api.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response?.status === 403) {
            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;
