import { request } from 'undici';
import { t } from '../i18n/translate.js';
const BASE = '/v1/ta/bury/manage/debug';
export class TEDebugClient {
    opts;
    constructor(opts) {
        this.opts = opts;
    }
    url(path, params) {
        const parts = [`@t=${Date.now()}`];
        for (const [k, v] of Object.entries(params)) {
            parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`);
        }
        return this.opts.host.replace(/\/$/, '') + BASE + path + '?' + parts.join('&');
    }
    async get(path, params) {
        const r = await request(this.url(path, params), {
            method: 'GET',
            headers: {
                authorization: `bearer ${this.opts.token}`,
                'x-requested-with': 'XMLHttpRequest',
                accept: 'application/json',
            },
        });
        const env = (await r.body.json());
        if (env.return_code !== 0) {
            if (env.return_code === -1001) {
                throw new Error(t('auth.token_expired_api'));
            }
            throw new Error(env.return_message || t('error.ae_error', { code: env.return_code }));
        }
        return env.data;
    }
    async listDevice(projectId) {
        const data = await this.get('/listDevice', { projectId });
        return data?.deviceList ?? [];
    }
    async addDevice(projectId, deviceId, deviceName) {
        await this.get('/saveDevice', { deviceId, deviceName, projectId });
    }
    async selectDevice(projectId, deviceId) {
        await this.get('/chooseDevice', { deviceId, projectId });
    }
    async removeDevice(projectId, deviceId) {
        await this.get('/deleteDevice', { deviceId, projectId });
    }
    async listDeviceData(projectId, deviceId, startTime) {
        const data = await this.get('/listDeviceData', {
            deviceID: deviceId, // NB uppercase D — matches AE backend
            projectId,
            startTime,
        });
        return data ?? { eventList: [], deviceDataList: [] };
    }
}
