import { HttpProject } from '../HttpProject.js';
import { Environment } from '../Environment.js';
/**
 * A class that transforms legacy export objects into API projects.
 * Note, this only cares about the HttpProject data. All other data are discarded.
 */
export class LegacyDataExportToApiProject {
    async readProjects(data) {
        const result = [];
        const { variables } = data;
        const projects = this.mapProjects(data.projects);
        const requests = this.mapRequests(data.requests);
        if (!projects.length || !requests.length) {
            return result;
        }
        const environments = this.createEnvironments(variables);
        const ps = projects.map(async (oldProject) => {
            const project = await HttpProject.fromLegacy(oldProject, [...requests]);
            environments.forEach((e) => project.addEnvironment(e));
            result.push(project);
        });
        await Promise.all(ps);
        return result;
    }
    mapRequests(items) {
        if (!Array.isArray(items)) {
            return [];
        }
        return items.map((item) => {
            const cp = { ...item };
            cp._id = item.key;
            // @ts-expect-error The key should be deleted.
            delete cp.key;
            return cp;
        });
    }
    mapProjects(items) {
        if (!Array.isArray(items)) {
            return [];
        }
        return items.map((item) => {
            const cp = { ...item };
            cp._id = item.key;
            // @ts-expect-error The key should be deleted.
            delete cp.key;
            return cp;
        });
    }
    createEnvironments(vars) {
        if (!Array.isArray(vars) || !vars.length) {
            return [];
        }
        const tmp = {};
        vars.forEach((variable) => {
            const { environment = 'default' } = variable;
            if (!tmp[environment]) {
                tmp[environment] = [];
            }
            tmp[environment].push(variable);
        });
        const result = [];
        Object.keys(tmp).forEach((name) => {
            const envVars = tmp[name];
            const environment = Environment.fromLegacyVariables(name, envVars);
            result.push(environment.toJSON());
        });
        return result;
    }
}
//# sourceMappingURL=LegacyDataExportToApiProject.js.map