import request from '@/utils/request';
import type {ApiResult, PageResult} from '@/api';
import type {ShopCart, ShopCartParam} from './model';
import {SERVER_API_URL} from "~/config";

/**
 * 分页查询购物车
 */
export async function pageShopCart(params: ShopCartParam) {
    const res = await request.get<ApiResult<PageResult<ShopCart>>>(
        SERVER_API_URL + '/shop/shop-cart/page',
        {
            params
        }
    );
    if (res.data.code === 0) {
        return res.data.data;
    }
    return Promise.reject(new Error(res.data.message));
}

/**
 * 查询购物车列表
 */
export async function listShopCart(params?: ShopCartParam) {
    const res = await request.get<ApiResult<ShopCart[]>>(
        SERVER_API_URL + '/shop/shop-cart',
        {
            params
        }
    );
    if (res.data.code === 0 && res.data.data) {
        return res.data.data;
    }
    return Promise.reject(new Error(res.data.message));
}

/**
 * 添加购物车
 */
export async function addShopCart(data: ShopCart) {
    const res = await request.post<ApiResult<unknown>>(
        SERVER_API_URL + '/shop/shop-cart',
        data
    );
    if (res.data.code === 0) {
        return res.data.message;
    }
    return Promise.reject(new Error(res.data.message));
}

/**
 * 修改购物车
 */
export async function updateShopCart(data: ShopCart) {
    const res = await request.put<ApiResult<unknown>>(
        SERVER_API_URL + '/shop/shop-cart',
        data
    );
    if (res.data.code === 0) {
        return res.data.message;
    }
    return Promise.reject(new Error(res.data.message));
}

/**
 * 删除购物车
 */
export async function removeShopCart(id?: number) {
    const res = await request.delete<ApiResult<unknown>>(
        SERVER_API_URL + '/shop/shop-cart/' + id
    );
    if (res.data.code === 0) {
        return res.data.message;
    }
    return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除购物车
 */
export async function removeBatchShopCart(data: (number | undefined)[]) {
    const res = await request.delete<ApiResult<unknown>>(
        SERVER_API_URL + '/shop/shop-cart/batch',
        {
            data
        }
    );
    if (res.data.code === 0) {
        return res.data.message;
    }
    return Promise.reject(new Error(res.data.message));
}

/**
 * 根据id查询购物车
 */
export async function getShopCart(id: number) {
    const res = await request.get<ApiResult<ShopCart>>(
        SERVER_API_URL + '/shop/shop-cart/' + id
    );
    if (res.data.code === 0 && res.data.data) {
        return res.data.data;
    }
    return Promise.reject(new Error(res.data.message));
}
