import type {ICartResponse} from "@/types/cart-response-d-t";
import type {ICart} from "@/types/cart-d-t";
import type {ICartItem} from "@/types/cart-item-d-t";
import type {ICartItemResponse} from "@/types/cart-item-response-d-t";
import {convertProductResponse} from "@/plugins/data/product-data";

export async function cartData(): Promise<ICart> {
    try {
        const response: { data: { data: ICartResponse } } = await $axios.get('cart');
        return convertCartResponse(response?.data?.data || {});
    } catch (error) {
        console.error('Error fetching cart data:', error);
        return {} as ICart;
    }
}

export function convertCartResponse(data: ICartResponse): ICart {
    return {
        cartItems: (data?.cartItems || []).map(convertCartItemResponse),
        fee_id: data?.fee_id,
        subtotal: data?.subtotal || 0,
        total: data?.total || 0
    };
}

export function convertCartItemResponse(data: ICartItemResponse): ICartItem {
    // @ts-ignore
    const product = data?.differents?.data || data?.differents || {}
    product.price = data?.price || product.calculated_price || product.price
    product.calculated_price = product.calculated_price || product.price

    return {
        // @ts-ignore
        id: data?.id || undefined,
        quantity: data?.quantity || 0,
        // @ts-ignore
        accessories: data?.accessories?.data || data?.accessories || [],
        // @ts-ignore
        differents: convertProductResponse(product),
    }
}

export default cartData;