"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchRemoteData = void 0;
const http = require("http");
const https = require("https");
const client_types_1 = require("@syftdata/common/lib/client_types");
function getEventSchema(event) {
    const fields = event.fields.map((field) => {
        const { name, ...fieldProps } = field;
        const val = {
            ...fieldProps,
            name,
            isOptional: field.isOptional,
            type: {
                name: field.type.name,
                zodType: field.type.zodType ?? 'z.any()'
            }
        };
        return val;
    });
    const schema = {
        name: event.name,
        documentation: event.documentation ?? '',
        fields,
        zodType: event.zodType,
        traits: [],
        eventType: client_types_1.SyftEventType[event.eventType]
    };
    return schema;
}
async function fetchRemoteData(baseUrl, apikey, branch) {
    if (process.env.NODE_ENV === 'test') {
        return;
    }
    const fullUrl = `${baseUrl}/api/cliinfo`;
    const payloadData = JSON.stringify({ branch });
    const options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': payloadData.length,
            'syft-cli-auth': apikey
        }
    };
    let protocol = http;
    if (baseUrl.includes('https')) {
        protocol = https;
    }
    return await new Promise((resolve, reject) => {
        const req = protocol.request(fullUrl, options, (res) => {
            if (res.statusCode !== undefined &&
                res.statusCode >= 200 &&
                res.statusCode <= 299) {
                const body = [];
                res.on('data', (d) => body.push(d));
                res.on('end', () => {
                    try {
                        const responseData = JSON.parse(Buffer.concat(body).toString());
                        const events = responseData.eventSchema.events;
                        const eventSchemas = events.map(getEventSchema);
                        resolve({
                            ast: {
                                config: {
                                    version: responseData.eventSchema.appVersion,
                                    projectName: responseData.eventSchema.appName
                                },
                                eventSchemas
                            },
                            activeBranch: responseData.activeBranch,
                            eventSchemaSha: responseData.eventSchemaSha,
                            tests: responseData.files
                        });
                    }
                    catch (e) {
                        reject(e);
                    }
                });
            }
            else {
                const body = [];
                res.on('data', (d) => body.push(d));
                res.on('end', () => {
                    try {
                        const responseData = JSON.parse(Buffer.concat(body).toString());
                        reject(new Error(responseData.message));
                    }
                    catch (e) {
                        reject(new Error(`statusCode=${res.statusCode ?? 'undefined'}`));
                    }
                });
            }
        });
        req.write(payloadData);
        req.end();
    });
}
exports.fetchRemoteData = fetchRemoteData;
