/**
 * 云服务平台适配器
 * 封装微信云开发 API
 */

export interface CloudResult {
    code?: string | number;
    message?: string;
    info?: string;
    data?: any;
    [key: string]: any;
}

/**
 * 调用云函数
 */
export async function callCloud(
    action: string,
    options?: Record<string, any>,
): Promise<CloudResult> {
    try {
        const name = 'doodle';

        const { errMsg, result } = await wx.cloud.callFunction({
            name,
            data: {
                action,
                ...options,
            },
        });
        if (!/ok/.test(errMsg)) {
            wx.showToast({
                title: '服务器错误',
                icon: 'none',
                duration: 2000,
            });
            return {
                code: '500',
                info: '服务器繁忙',
                message: errMsg,
            };
        }
        return result as CloudResult;
    } catch (e: any) {
        return { code: '500', info: e.message || '服务器繁忙' };
    }
}

/**
 * 查询云数据库集合
 */
export async function queryCollection(
    collection: string,
    where?: Record<string, any>,
    limit: number = 20,
    orderBy?: { field: string; order: 'asc' | 'desc' },
): Promise<any[]> {
    try {
        const db = wx.cloud.database();
        let query = db.collection(collection).where(where || {}).limit(limit);
        if (orderBy) {
            query = query.orderBy(orderBy.field, orderBy.order);
        }
        const { data } = await query.get();
        return data;
    } catch (e) {
        console.error('queryCollection failed:', collection, e);
        return [];
    }
}
