import axios from 'axios';

// Tenant Extraction Logic
export const getTenantFromSubdomain = (): string => {
    const hostname = window.location.hostname;

    // Localhost or IP address -> 'public' (or dev tenant)
    if (hostname === 'localhost' || hostname === '127.0.0.1') {
        return 'public';
    }

    // Extract subdomain
    // e.g., plumbing.chronoflow.com -> plumbing
    const parts = hostname.split('.');
    if (parts.length > 2) {
        return parts[0];
    }

    return 'public'; // Fallback
};

// Axios Instance
const api = axios.create({
    baseURL: import.meta.env.VITE_API_URL || 'http://localhost:8000/api',
    withCredentials: true, // Important for cookies/sessions
});

// Request Interceptor to inject Tenant ID
api.interceptors.request.use((config) => {
    const tenant = getTenantFromSubdomain();
    if (tenant) {
        config.headers['X-Tenant-ID'] = tenant;
    }
    return config;
});

export default api;
