const objectql = require('@steedos/objectql');

module.exports = {
    rest: {
        method: 'GET',
        fullPath: '/api/workflow/pages/schema'
    },
    params: {
        pageId: { type: 'string' }
    },
    async handler(ctx) {
        const { pageId } = ctx.params;
        const userSession = ctx.meta.user;

        if (!pageId) {
            return {};
        }

        // 直接 broker.call page.getMeSchema 获取页面 schema
        // 参考 steedos-platform/services/service-pages/main/default/routes/page_schema.router.js
        // flow_selector 这个 page 的 type 固定为 'page'
        const result = await objectql.getSteedosSchema().broker.call('page.getMeSchema', {
            type: 'page',
            pageId: pageId
        }, {
            meta: { user: userSession }
        });

        if (!result || !result.schema) {
            return {};
        }

        // result.schema 可能是字符串（JSON）或对象，统一处理
        let schema = result.schema;
        if (typeof schema === 'string') {
            try {
                schema = JSON.parse(schema);
            } catch (e) {
                return {};
            }
        }

        // 返回与旧接口一致的结构，包含 inject + assets（tailwind CSS）+ body
        // 参考 steedos-platform/services/service-pages/main/default/functions/pages_schema.function.yml
        return {
            type: 'inject',
            assets: [
                {
                    type: 'css',
                    id: 'page-css',
                    src: `/api/v6/pages/${pageId}/current/tailwind.css`,
                    location: 'start'
                }
            ],
            body: [schema]
        };
    }
};
