import { request } from 'undici';
import { t } from '../i18n/translate.js';
const PLAN_PATH = '/v1/ta/bury/manage/program/query';
export async function fetchPlan({ projectId, host, token }) {
    const url = `${host.replace(/\/$/, '')}${PLAN_PATH}?@t=${Date.now()}&projectId=${projectId}`;
    const { statusCode, body } = await request(url, {
        method: 'GET',
        headers: {
            authorization: `bearer ${token}`,
            'x-requested-with': 'XMLHttpRequest',
        },
    });
    if (statusCode !== 200) {
        const text = await body.text();
        throw new Error(t('error.fetch_failed', { statusCode, body: text.slice(0, 200) }));
    }
    const payload = (await body.json());
    if (payload.return_code !== 0) {
        if (payload.return_code === -1001) {
            throw new Error(`AE token expired or invalid (return_code -1001). Re-login in Chrome, then run: ae-tracking auth login`);
        }
        throw new Error(t('error.fetch_return_code', { code: payload.return_code, message: payload.return_message ?? '' }));
    }
    if (!payload.data) {
        throw new Error(t('error.fetch_no_data', { host }));
    }
    return normalize(payload.data);
}
function normalize(data) {
    if (!data) {
        return { meta: { app_type: 'unknown', sdk_integration_mode: 'client_only', plan_name: 'from-te' }, events: [], event_properties: [], common_event_properties: [], user_properties: [] };
    }
    return {
        meta: { app_type: 'unknown', sdk_integration_mode: 'client_only', plan_name: 'from-te' },
        events: (data.events ?? []).map((e) => ({
            event_name: e.eventName,
            display_name: e.displayName,
            event_tag: e.eventTag,
            event_desc: e.eventDesc,
            source: 'chat',
            prop_names: e.props ?? [],
        })),
        event_properties: (data.eventProps ?? []).map((p) => ({
            name: p.name, display_name: p.displayName, type: (p.type?.toLowerCase() ?? 'string'), desc: p.desc, source: 'chat',
        })),
        common_event_properties: (data.commonEventProps ?? []).map((p) => ({
            name: p.name, display_name: p.displayName, type: (p.type?.toLowerCase() ?? 'string'), desc: p.desc, source: 'chat',
        })),
        user_properties: (data.userProps ?? []).map((p) => ({
            name: p.name, display_name: p.displayName, type: (p.type?.toLowerCase() ?? 'string'), desc: p.desc,
            update_type: (p.updateType ?? 'user_set'), prop_tag: p.propTag, source: 'chat',
        })),
    };
}
