import type {ICategory} from "@/types/category-d-t";
import type {ICategoryResponse} from "@/types/category-response-d-t";
import {convertProductResponse} from "@/plugins/data/product-data";
import toolsService from "@/services/toolsService";

export async function categoryFeaturedData({
                                               prepend = [],
                                               append = [],
                                               page = 1,
                                               slug = "",
                                               plain = false,
                                               url = false,
                                               baseUrl = undefined,
                                               noImageUrl = undefined
                                           }: {
    prepend?: ICategory[];
    append?: ICategory[];
    page?: number;
    slug?: string;
    plain?: boolean;
    url?: boolean;
    baseUrl?: string;
    noImageUrl?: string;
} = {}): Promise<ICategory[]> {
    try {
        page = Number(page) || 1;
        page = page < 1 ? 1 : page;
        const response: { data: { data: ICategoryResponse[] } } = await $axios.get(`categories/featured?page=${page}`);
        const categories = response?.data?.data || [];
        const transformedCategories: Awaited<ICategory>[] = await Promise.all(categories.map((x: ICategoryResponse)=>convertCategoryFeaturedResponse(x, noImageUrl)));
        return [...prepend, ...transformedCategories, ...append];
    } catch (error) {
        console.error('Error fetching category featured data:', error);
        return [];
    }
}

export function convertCategoryFeaturedResponse(category: ICategoryResponse, noImage?: string): ICategory {
    return {
        ITYPE: 'category',
        id: category.id,
        slug: category.slug,
        // url: `/category/${category.slug}`,
        url: toolsService.getCategoryUrl(category),
        img: category.imageUrl,
        preName: category.prename,
        parentName: category.name,
        products: (category?.products?.data || []).map(x => convertProductResponse(x, noImage)),
        children: category?.sub_categories?.data/*.map((subCategory) => subCategory.id)*/,
        textClr: category.textClr || undefined,
    };
}

export default categoryFeaturedData;