import { getCubePlatformUserId } from './get-cube-platform-user-id';
import { CUBE_PLATFORM_CREATE_OR_UPDATE_URL } from '../../../cn-ai-table/view/constants/cube-platform-view-constants';
import { requestCubeOpenPlatform } from './merge-cube-platform-request';
import { parseCreateOrUpdateRowId } from './parse-response';
function resolveUserCubePrimaryKey(rowIdFromList, userCubeConfigRowIdHint, nextConfig) {
    const idFromList = rowIdFromList && String(rowIdFromList).trim() !== '' ? String(rowIdFromList).trim() : '';
    const idFromHint = userCubeConfigRowIdHint && String(userCubeConfigRowIdHint).trim() !== ''
        ? String(userCubeConfigRowIdHint).trim()
        : '';
    const idFromParsed = nextConfig.id != null && String(nextConfig.id).trim() !== ''
        ? String(nextConfig.id).trim()
        : '';
    return idFromList || idFromHint || idFromParsed;
}
export async function submitUserCubeCreateOrUpdate(options) {
    var _a, _b;
    const { meta, rowIdFromList, userCubeConfigRowIdHint, nextConfig, bizRequestConfig } = options;
    try {
        const pk = resolveUserCubePrimaryKey(rowIdFromList, userCubeConfigRowIdHint, nextConfig);
        const restOfUserCube = { ...nextConfig };
        delete restOfUserCube.id;
        const body = { id: pk, ...restOfUserCube };
        const data = {
            content: JSON.stringify(body),
            pageId: meta.pageId,
            userId: getCubePlatformUserId(meta),
            appCode: meta.appCode,
            tenantCode: (_a = meta.tenantCode) !== null && _a !== void 0 ? _a : '',
            loginType: meta.loginType,
            id: pk,
        };
        if (meta.userName !== undefined && meta.userName !== null) {
            data.userName = meta.userName;
        }
        const couRequestConfig = (_b = bizRequestConfig === null || bizRequestConfig === void 0 ? void 0 : bizRequestConfig.cubePlatform) === null || _b === void 0 ? void 0 : _b.createOrUpdateRequestConfig;
        const result = await requestCubeOpenPlatform(CUBE_PLATFORM_CREATE_OR_UPDATE_URL, data, couRequestConfig, 'POST');
        const newId = parseCreateOrUpdateRowId(result);
        return { success: true, userCubeConfigRowId: newId || pk || '' };
    }
    catch (error) {
        return { success: false, errorMsg: error };
    }
}
