"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeViewsResponse = normalizeViewsResponse;
exports.queryTableViews = queryTableViews;
exports.saveTableViews = saveTableViews;
/**
 * **仅源码场景**：用户在 `viewConfig` 里手动配置 `queryViewsUrl` / `saveViewsUrl` 时，走业务侧 HTTP（与直连开放平台互斥，见 `index.ts`）。
 *
 * 未配上述 URL 时由 `open-platform/` 下直连 getList 等；与后者互斥（见 `../index.ts`）。
 */
const cn_request_1 = require("@cainiaofe/cn-request");
const domain_service_1 = require("../../../service/domain-service.js");
/** 将业务接口或 `tableView` 原始数据的多层包结构规整为 `ViewsData`（直连读路径复用） */
function normalizeViewsResponse(raw) {
    const empty = { views: {}, viewOrder: [] };
    if (raw == null || typeof raw !== 'object') {
        return empty;
    }
    let obj = raw;
    if ('data' in obj && obj.data && typeof obj.data === 'object') {
        const inner = obj.data;
        if ('views' in inner) {
            obj = inner;
        }
    }
    if (!('views' in obj) || typeof obj.views !== 'object' || obj.views === null) {
        return empty;
    }
    /** 与魔方 / `getTableView` 对齐：除 `views` / `viewOrder` 外原样透传（如 customFields 及后续扩展字段），避免源码路径丢配置 */
    const normalized = {
        ...obj,
        views: obj.views,
        viewOrder: Array.isArray(obj.viewOrder) ? obj.viewOrder : [],
    };
    return normalized;
}
/** 源码配置 `queryViewsUrl` 时拉取视图；无 URL 或失败则空 */
async function queryTableViews(tableId, bizRequestConfig) {
    var _a, _b;
    const url = (_a = bizRequestConfig === null || bizRequestConfig === void 0 ? void 0 : bizRequestConfig.viewConfig) === null || _a === void 0 ? void 0 : _a.queryViewsUrl;
    if (!url) {
        return { views: {}, viewOrder: [] };
    }
    try {
        const result = await (0, cn_request_1.request)({
            url,
            method: 'GET',
            params: { tableId },
            withCredentials: (0, domain_service_1.isUsingDynamicDomain)(),
        });
        const raw = (_b = result === null || result === void 0 ? void 0 : result.data) !== null && _b !== void 0 ? _b : result;
        return normalizeViewsResponse(raw);
    }
    catch {
        return { views: {}, viewOrder: [] };
    }
}
/** 源码配置 `saveViewsUrl` 时持久化视图；无 URL 则 no-op */
async function saveTableViews(params, bizRequestConfig) {
    var _a;
    const url = (_a = bizRequestConfig === null || bizRequestConfig === void 0 ? void 0 : bizRequestConfig.viewConfig) === null || _a === void 0 ? void 0 : _a.saveViewsUrl;
    if (!url) {
        return;
    }
    await (0, cn_request_1.request)({
        url,
        method: 'POST',
        data: params,
        withCredentials: (0, domain_service_1.isUsingDynamicDomain)(),
    });
}
