import { oneDayInMs, oneMonthInMs } from '../../shared/utils.js';
import { getConfig } from '../config.js';
import { inDateRange } from './helpers.js';
import { ReleaseModel } from './mongoose-models/ReleaseEnvironment.js';
import { fromContext } from './utils.js';
export const getReleaseUpdateDates = (collectionName, project) => ReleaseModel.aggregate([
    {
        $match: {
            collectionName,
            project,
            modifiedOn: { $gt: new Date(oneDayInMs * 30 * 6) },
        },
    },
    {
        $project: {
            date: {
                $max: ['$environments.deploySteps.lastModifiedOn', '$modifiedOn', '$createdOn'],
            },
            id: '$id',
        },
    },
]);
export const getReleases = (collectionName, project, queryFrom = getConfig().azure.queryFrom) => ReleaseModel.aggregate([
    {
        $match: {
            collectionName,
            project,
            modifiedOn: { $gt: new Date(queryFrom.getTime() - oneMonthInMs) },
        },
    },
    {
        $addFields: {
            computedLastUpdate: {
                $max: ['$environments.deploySteps.lastModifiedOn', '$modifiedOn', '$createdOn'],
            },
        },
    },
    { $match: { computedLastUpdate: { $gt: queryFrom } } },
]);
export const getPipelinesCount = (collectionName, project, queryFrom = getConfig().azure.queryFrom) => ReleaseModel.aggregate([
    {
        $match: {
            collectionName,
            project,
            'environments.deploySteps.queuedOn': { $gt: queryFrom },
        },
    },
    { $group: { _id: '$releaseDefinitionId' } },
    { $count: 'count' },
]).then(result => { var _a; return ((_a = result[0]) === null || _a === void 0 ? void 0 : _a.count) || 0; });
export const pipelineCountForRepo = (queryContext, repoId) => {
    const { collectionName, project, startDate, endDate } = fromContext(queryContext);
    return ReleaseModel.aggregate([
        {
            $match: {
                'collectionName': collectionName,
                'project': project,
                'environments.deploySteps.queuedOn': inDateRange(startDate, endDate),
                'artifacts.definition.repositoryId': repoId,
            },
        },
        {
            $group: {
                _id: '$releaseDefinitionId',
            },
        },
        { $count: 'count' },
    ]).then(result => { var _a; return ((_a = result[0]) === null || _a === void 0 ? void 0 : _a.count) || 0; });
};
