import { collectionsAndProjects, getConfig } from '../config.js';
import { AzureBuildReportModel } from '../models/build-reports/index.js';
import { BuildDefinitionModel } from '../models/mongoose-models/BuildDefinitionModel.js';
import { BuildModel } from '../models/mongoose-models/BuildModel.js';
import { TestRunModel } from '../models/mongoose-models/TestRunModel.js';
import azure from '../scraper/network/azure.js';
import { invokeSeries } from '../utils.js';
export const bulkSaveBuildDefinitions = (collectionName, project) => async (buildDefinitions) => {
    // Delete any pipelines that have been deleted from Azure
    await BuildDefinitionModel.deleteMany({
        collectionName,
        project,
        id: { $nin: buildDefinitions.map(b => b.id) },
    });
    await BuildModel.deleteMany({
        collectionName,
        project,
        'definition.id': { $nin: buildDefinitions.map(b => b.id) },
    });
    await TestRunModel.deleteMany({
        collectionName,
        'project.name': project,
        'buildConfiguration.buildDefinitionId': { $nin: buildDefinitions.map(b => b.id) },
    });
    await BuildDefinitionModel.bulkWrite(buildDefinitions.map(buildDefinition => {
        var _a;
        const { project, process, ...rest } = buildDefinition;
        const processForDB = process.type === 2
            ? {
                processType: 2,
                yamlFilename: process.yamlFilename,
            }
            : { processType: 1 };
        return {
            updateOne: {
                filter: {
                    collectionName,
                    project: project.name,
                    id: buildDefinition.id,
                },
                update: {
                    $set: {
                        process: processForDB,
                        repositoryId: (_a = buildDefinition.repository) === null || _a === void 0 ? void 0 : _a.id,
                        ...rest,
                    },
                },
                upsert: true,
            },
        };
    }));
    await AzureBuildReportModel.deleteMany({
        collectionName,
        project,
        buildDefinitionId: { $nin: buildDefinitions.map(b => String(b.id)) },
    });
};
export const getBuildDefinitions = () => {
    const { getBuildDefinitions } = azure(getConfig());
    return invokeSeries(collectionsAndProjects(), async ([collection, project]) => {
        return getBuildDefinitions(collection.name, project.name).then(bulkSaveBuildDefinitions(collection.name, project.name));
    });
};
