/**
 * Anjaneyulu.in - API Service Layer
 * Centralized API calls for the application.
 */

const API_ROOT = "http://localhost:3000/api";

const API = {
    async get(endpoint) {
        const token = localStorage.getItem('anj_token');
        const res = await fetch(`${API_ROOT}${endpoint}`, {
            headers: { 'Authorization': `Bearer ${token}` }
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.message || 'API Error');
        return data;
    },

    async post(endpoint, body) {
        let token = localStorage.getItem('anj_token');
        
        // Guest token support for public form submissions
        if (!token && endpoint === '/leads') {
            token = 'guest-token-anjaneyulu';
        }
        
        const res = await fetch(`${API_ROOT}${endpoint}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(body)
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.message || 'API Error');
        return data;
    },

    async patch(endpoint, body) {
        const token = localStorage.getItem('anj_token');
        const res = await fetch(`${API_ROOT}${endpoint}`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(body)
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.message || 'API Error');
        return data;
    },

    // Specific Domain Methods
    Leads: {
        getAll: () => API.get('/leads'),
        create: (data) => API.post('/leads', data),
        updateStatus: (id, status, sub_stage) => API.patch(`/leads/${id}/status`, { status, sub_stage }),
        updatePending: (id, pending_status, pending_remarks) => API.patch(`/leads/${id}/pending`, { pending_status, pending_remarks })
    },

    Users: {
        getAll: () => API.get('/users'),
        updateRole: (id, role) => API.patch(`/users/${id}/role`, { role }),
        toggleStatus: (id) => API.patch(`/users/${id}/toggle-status`, {})
    },

    Properties: {
        getAll: () => API.get('/properties'),
        create: (data) => API.post('/properties', data),
        updateStatus: (id, data) => {
            const body = typeof data === 'object' ? data : { status: data };
            return API.patch(`/properties/${id}/status`, body);
        },
        update: (id, data) => API.put(`/properties/${id}`, data)
    },

    Products: {
        getAll: () => API.get('/products'),
        getAdminAll: () => API.get('/products/admin'),
        create: (data) => API.post('/products', data),
        update: (id, data) => API.patch(`/products/${id}`, data)
    },

    Orders: {
        place: (data) => API.post('/orders', data),
        getMyOrders: () => API.get('/orders/my-orders'),
        getAdminAll: () => API.get('/orders/admin/all'),
        updateStatus: (id, data) => API.patch(`/orders/${id}/status`, data)
    },

    Pincodes: {
        get: (pincode) => API.get(`/pincodes/${pincode}`)
    }
};
