import axios from 'axios';

const BACKEND_URL = process.env.REACT_APP_BACKEND_URL || '';
export const API = `${BACKEND_URL}/api`;

export const api = axios.create({ baseURL: API });

api.interceptors.request.use((config) => {
    const token = localStorage.getItem('mytruck_token');
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
});

api.interceptors.response.use(
    (r) => r,
    (err) => {
        const url = err?.config?.url || '';
        const isAuthEndpoint = url.includes('/auth/login') || url.includes('/auth/sso');
        if (err?.response?.status === 401 && !isAuthEndpoint) {
            localStorage.removeItem('mytruck_token');
            localStorage.removeItem('mytruck_user');
            if (window.location.pathname !== '/login' && window.location.pathname !== '/sso') {
                window.location.href = '/login';
            }
        }
        return Promise.reject(err);
    }
);

export function buildWsUrl(token) {
    const base = BACKEND_URL || window.location.origin;
    const url = new URL(base);
    const proto = url.protocol === 'https:' ? 'wss:' : 'ws:';
    return `${proto}//${url.host}/api/ws/notifications?token=${encodeURIComponent(token)}`;
}
