import axios from 'axios';
import { WP_API_CONFIG } from '../config/wordpress';

const api = axios.create({
    baseURL: WP_API_CONFIG.BASE_URL,
    headers: {
        'Content-Type': 'application/json',
    },
});

export const wpApi = {
    /**
     * Fetch latest posts
     * @param {number} page - Page number
     * @param {number} perPage - Posts per page
     */
    getPosts: async (page = 1, perPage = WP_API_CONFIG.PER_PAGE, categoryId = null) => {
        try {
            const params = {
                page,
                per_page: perPage,
                _embed: true, // Include featured images, author info, etc.
            };

            if (categoryId) {
                params.categories = categoryId;
            }

            const response = await api.get(WP_API_CONFIG.ENDPOINTS.POSTS, { params });
            return {
                data: response.data,
                total: parseInt(response.headers['x-wp-total'], 10),
                totalPages: parseInt(response.headers['x-wp-totalpages'], 10),
            };
        } catch (error) {
            console.error('Error fetching posts:', error);
            throw error;
        }
    },

    /**
     * Fetch a single post by slug
     * @param {string} slug 
     */
    getPostBySlug: async (slug) => {
        try {
            const response = await api.get(WP_API_CONFIG.ENDPOINTS.POSTS, {
                params: {
                    slug,
                    _embed: true,
                },
            });
            return response.data[0];
        } catch (error) {
            console.error('Error fetching post by slug:', error);
            throw error;
        }
    },

    /**
     * Fetch a page by slug (e.g., 'about', 'contact')
     * @param {string} slug 
     */
    getPageBySlug: async (slug) => {
        try {
            const response = await api.get(WP_API_CONFIG.ENDPOINTS.PAGES, {
                params: {
                    slug,
                    _embed: true,
                },
            });
            return response.data[0];
        } catch (error) {
            console.error('Error fetching page by slug:', error);
            throw error;
        }
    },

    /**
     * Fetch categories
     * @param {string} slug - Optional slug to filter by
     */
    getCategories: async (slug = null) => {
        try {
            const params = {};
            if (slug) {
                params.slug = slug;
            }
            const response = await api.get(WP_API_CONFIG.ENDPOINTS.CATEGORIES, { params });
            return response.data;
        } catch (error) {
            console.error('Error fetching categories:', error);
            throw error;
        }
    }
};
