import type {IReview} from "@/types/review-d-t";
import type {IReviewResponse} from "@/types/review-response-d-t";
import type {IProduct} from "@/types/product-d-t";
import toolsService from "@/services/toolsService";
import type {TPagination, TPaginationOr} from "@/types/pagination-d-t";

export async function productReviewsData({page = 1, slug = '', product = undefined,
                                             plain= false,
                                             pagination= false,}: {
    page?: number,
    slug?: string,
    product?: IProduct|null,
    plain?: boolean,
    pagination?: boolean,
} = {}): Promise<TPaginationOr<(IReview | IReviewResponse)[]>> {
    try {
        // console.warn(8,{prepend, append, page, slug})
        if (page) {
            page = Number(page) || 1;
            page = page < 1 ? 1 : page;
        }

        slug = (product ? toolsService.id(product) : slug) || useRoute()?.params?.product as string;
        if (slug) {
            // let id = String(slug.split('-').shift());
            // slug = id ? `/${id}/products` : '';
            slug = toolsService.getSlug(slug, {prefix: '/'});
        }

        const url = `products${slug || ''}/reviews?` + (page ? `page=${page}` : '');
        const response: { data: { data: IReviewResponse[] } } = await $axios.get(url);
        if (plain) {
            if (pagination) {
                // @ts-ignore
                return (response?.data || []) as TPagination<(IReview | IReviewResponse)[]>;
            }

            // @ts-ignore
            return (response?.data?.data || []) as IReviewResponse[];
        }

        return await Promise.all((response?.data?.data || []).map(convertProductReviewResponse)) as IReviewResponse[];
    } catch (error) {
        console.error('Error fetching product reviews data:', error);
        return [];
    }
}

export function convertProductReviewResponse(review: IReviewResponse): IReview {
    return {
        ITYPE: "review",
        id: review?.id,
        comment: review.comment,
        rating: review.rating,
        user: review.user,
        date: review.date
    };
}

export default productReviewsData;