import axios, { AxiosRequestConfig } from 'axios';
import { BASE_API_PATH } from '../config/apiConfig';

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

// Request interceptor to add the auth token to headers
// This mirrors the logic in `UserInfoService.getStoredToken` and `ApiRequestService.getHeaders`
apiService.interceptors.request.use((config) => {
    // In Angular, user info is stored in sessionStorage under "currentUser"
    const currentUserStr = sessionStorage.getItem('currentUser');
    if (currentUserStr) {
        const currentUser = JSON.parse(currentUserStr);
        if (currentUser && currentUser.token) {
            if (config.headers) {
                // The Angular service just adds the token, not "Bearer". We will follow that.
                config.headers['Authorization'] = currentUser.token;
            }
        }
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

// Response interceptor for global error handling
// This is a more robust version of `ApiRequestService.handleError`
apiService.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response) {
            console.error("API Error Response:", error.response);
            const { status } = error.response;
            let errorMessage = 'Server Error';

            switch (status) {
                case 401:
                    errorMessage = 'Forbidden. Please check your credentials or login again.';
                    // In a real app, you'd likely redirect to the login page here.
                    // e.g., window.location.href = '/login';
                    break;
                case 404:
                    errorMessage = 'The requested resource was not found.';
                    break;
                case 408:
                    errorMessage = 'The request timed out.';
                    break;
                case 500:
                    errorMessage = 'An internal server error occurred.';
                    break;
                default:
                    errorMessage = error.response.data?.message || 'An unexpected error occurred.';
            }
            return Promise.reject(new Error(errorMessage));
        } else if (error.request) {
            console.error("API Error Request (no response received):", error.request);
            return Promise.reject(new Error('Network error. Please check your connection and try again.'));
        } else {
            console.error('API Setup Error:', error.message);
            return Promise.reject(new Error(error.message));
        }
    }
);

export default apiService;

/**
 * A dedicated function for POSTing multipart/form-data.
 * This is based on `ApiRequestService.postFormData`.
 * @param url The endpoint URL (relative to base path).
 * @param formData The FormData object to send.
 * @returns A promise with the axios response.
 */
export const postFormData = (url: string, formData: FormData) => {
    return apiService.post(url, formData, {
        headers: {
            'Content-Type': 'multipart/form-data',
        },
    });
};
