/**
 * js/api.js
 * Handles API interactions, with a mockup mode and a real API readiness.
 */

const MOCK_API_DELAY = 800; // Simulate network latency in milliseconds
const USE_MOCK_API = true; // Set to false to connect to real API

// --- Configuration for Real API (if USE_MOCK_API is false) ---
const REAL_API_BASE_URL = 'http://your-real-api.com/api'; // Replace with your actual API base URL

// --- Mockup API Data ---
let mockupCarsData = []; // Will be loaded from data/cars.json

async function loadMockupData() {
    if (mockupCarsData.length === 0) {
        try {
            const response = await fetch('data/cars.json');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            mockupCarsData = await response.json();
            console.log("Mockup cars data loaded successfully.", mockupCarsData);
        } catch (error) {
            console.error("Failed to load mockup car data:", error);
            // Fallback to empty array or predefined static data
            mockupCarsData = []; 
        }
    }
}

// --- API Implementation ---
const api = {
    async get(endpoint, params = {}) {
        if (USE_MOCK_API) {
            await loadMockupData(); // Ensure mockup data is loaded
            return new Promise(resolve => {
                setTimeout(() => {
                    let dataToReturn;
                    let success = true;

                    if (endpoint === '/cars') {
                        // Simulate filtering logic for cars
                        dataToReturn = mockupCarsData.filter(car => {
                            let matches = true;
                            // Example filtering: Add more complex date/location filtering here if needed
                            if (params.type && car.type.toLowerCase() !== params.type.toLowerCase()) {
                                matches = false;
                            }
                            // Simple availability check based on mockup `available` field
                            if (params.available !== undefined && car.available !== params.available) {
                                matches = false;
                            }
                            return matches;
                        });
                        if (dataToReturn.length === 0 && Object.keys(params).length > 0) {
                             success = false; // No cars found for filters
                        }
                    } else if (endpoint.startsWith('/cars/')) {
                        const carId = endpoint.split('/')[2];
                        dataToReturn = mockupCarsData.find(car => car.id === carId);
                        if (!dataToReturn) {
                            success = false; // Car not found
                        }
                    } else if (endpoint === '/user/profile') {
                        // Simulate fetching user profile
                        dataToReturn = { id: 'user123', name: 'Mock User', email: 'mock@example.com' };
                    }
                    else {
                        success = false; // Unknown endpoint
                        dataToReturn = null;
                    }

                    resolve({ success, data: dataToReturn, message: success ? 'OK' : 'Resource not found or failed to filter.' });
                }, MOCK_API_DELAY);
            });
        } else {
            // --- Real API connection ---
            try {
                const queryParams = new URLSearchParams(params).toString();
                const url = `${REAL_API_BASE_URL}${endpoint}${queryParams ? `?${queryParams}` : ''}`;
                const response = await fetch(url);

                if (!response.ok) {
                    throw new Error(`API error! status: ${response.status}`);
                }
                const data = await response.json();
                return { success: true, data };
            } catch (error) {
                console.error(`Error fetching ${endpoint}:`, error);
                return { success: false, message: error.message };
            }
        }
    },

    async post(endpoint, data) {
        if (USE_MOCK_API) {
            return new Promise(resolve => {
                setTimeout(() => {
                    let success = true;
                    let message = "Operation successful";
                    let responseData = null;

                    if (endpoint === '/bookings') {
                        // Simulate a successful booking
                        console.log("Mock API: Booking received", data);
                        responseData = { bookingId: `BOOK-${Date.now()}`, status: 'pending', ...data };
                        message = "Booking created successfully!";
                    } else if (endpoint === '/auth/login') {
                        // Simulate login
                        console.log("Mock API: Login attempt", data);
                        if (data.username === 'user' && data.password === 'pass') {
                            responseData = { token: 'mock-jwt-token', user: { name: 'Mock User', email: data.username } };
                            message = "Login successful!";
                        } else {
                            success = false;
                            message = 'Invalid username or password.';
                        }
                    } else {
                        success = false;
                        message = 'Unknown POST endpoint.';
                    }
                    resolve({ success, data: responseData, message });
                }, MOCK_API_DELAY);
            });
        } else {
            // --- Real API connection ---
            try {
                const response = await fetch(`${REAL_API_BASE_URL}${endpoint}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        // 'Authorization': `Bearer ${localStorage.getItem('token')}` // Example for authenticated requests
                    },
                    body: JSON.stringify(data)
                });

                const responseData = await response.json();

                if (!response.ok) {
                    throw new Error(responseData.message || `API error! status: ${response.status}`);
                }
                return { success: true, data: responseData, message: responseData.message || 'Operation successful.' };
            } catch (error) {
                console.error(`Error posting to ${endpoint}:`, error);
                return { success: false, message: error.message };
            }
        }
    }
};

export default api;