import { client } from './client.js'

export async function getCategories() {
    const response = await client.get('/items/categories', {
        fields: ['*', 'translations.*'],
        filter: { status: { _eq: 'published' } },
        sort: ['sort', 'name'],
        limit: -1
    })
    return response.data || []
}

export async function getCategory(idOrSlug) {
    const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(idOrSlug)

    if (isUuid) {
        const response = await client.get(`/items/categories/${idOrSlug}`, {
            fields: ['*', 'translations.*', 'parent.*']
        })
        return response.data
    }

    const response = await client.get('/items/categories', {
        fields: ['*', 'translations.*', 'parent.*'],
        filter: { slug: { _eq: idOrSlug } },
        limit: 1
    })
    return response.data?.[0] || null
}

export async function getCategoryTree() {
    const categories = await getCategories()
    return buildCategoryTree(categories)
}

export function buildCategoryTree(categories, parentId = null) {
    return categories
        .filter(cat => (cat.parent?.id || cat.parent) === parentId)
        .map(cat => ({
            ...cat,
            children: buildCategoryTree(categories, cat.id)
        }))
}

export async function getSubcategories(parentId) {
    const response = await client.get('/items/categories', {
        fields: ['*', 'translations.*'],
        filter: {
            status: { _eq: 'published' },
            parent: { _eq: parentId }
        },
        sort: ['sort', 'name']
    })
    return response.data
}
