import { z } from 'zod';
import { PullRequestModel } from './mongoose-models/PullRequestModel.js';
import { inDateRange } from './helpers.js';
import { queryContextInputParser, fromContext, weekIndexValue } from './utils.js';
export const PullRequestsSummaryForRepoInputParser = z.object({
    queryContext: queryContextInputParser,
    repositoryId: z.string(),
});
export const getPullRequestsSummaryForRepo = async ({ queryContext, repositoryId, }) => {
    var _a, _b, _c, _d, _e, _f;
    const { collectionName, project, startDate, endDate } = fromContext(queryContext);
    const prStats = await PullRequestModel.aggregate([
        {
            $match: {
                collectionName,
                project,
                repositoryId,
                $or: [
                    { status: 'active' },
                    {
                        status: { $in: ['abandoned', 'completed'] },
                        closedDate: inDateRange(startDate, endDate),
                    },
                ],
            },
        },
        {
            $addFields: {
                timeCompleted: {
                    $cond: {
                        if: { $eq: ['$status', 'completed'] },
                        then: {
                            $dateDiff: {
                                startDate: '$creationDate',
                                endDate: '$closedDate',
                                unit: 'millisecond',
                            },
                        },
                        else: 0,
                    },
                },
            },
        },
        {
            $group: {
                _id: '$status',
                total: { $sum: 1 },
                minTime: { $min: '$timeCompleted' },
                maxTime: { $max: '$timeCompleted' },
                avgTime: { $avg: '$timeCompleted' },
            },
        },
        {
            $project: {
                _id: 0,
                prStatus: '$_id',
                total: 1,
                minTime: 1,
                maxTime: 1,
                avgTime: 1,
            },
        },
    ]);
    return {
        active: ((_a = prStats.find((pr) => pr.prStatus === 'active')) === null || _a === void 0 ? void 0 : _a.total) || 0,
        abandoned: ((_b = prStats.find((pr) => pr.prStatus === 'abandoned')) === null || _b === void 0 ? void 0 : _b.total) || 0,
        completed: ((_c = prStats.find((pr) => pr.prStatus === 'completed')) === null || _c === void 0 ? void 0 : _c.total) || 0,
        minTime: ((_d = prStats.find((pr) => pr.prStatus === 'completed')) === null || _d === void 0 ? void 0 : _d.minTime) || 0,
        maxTime: ((_e = prStats.find((pr) => pr.prStatus === 'completed')) === null || _e === void 0 ? void 0 : _e.maxTime) || 0,
        avgTime: ((_f = prStats.find((pr) => pr.prStatus === 'completed')) === null || _f === void 0 ? void 0 : _f.avgTime) || 0,
    };
};
export const getTotalPullRequestsForRepositoryIds = async (queryContext, repositoryIds) => {
    const { collectionName, project, startDate, endDate } = fromContext(queryContext);
    return PullRequestModel.aggregate([
        {
            $match: {
                collectionName,
                project,
                repositoryId: { $in: repositoryIds },
                $or: [
                    { status: 'active' },
                    {
                        status: { $in: ['abandoned', 'completed'] },
                        closedDate: inDateRange(startDate, endDate),
                    },
                ],
            },
        },
        { $group: { _id: '$repositoryId', total: { $sum: 1 } } },
        {
            $project: {
                _id: 0,
                repositoryId: '$_id',
                total: 1,
            },
        },
    ]).exec();
};
export const getWeeklyPullRequestMerges = async (queryContext, repositoryIds) => {
    const { collectionName, project, startDate, endDate } = fromContext(queryContext);
    return PullRequestModel.aggregate([
        {
            $match: {
                collectionName,
                project,
                repositoryId: { $in: repositoryIds },
                closedDate: inDateRange(startDate, endDate),
                status: 'completed',
            },
        },
        { $addFields: { weekIndex: weekIndexValue(startDate, '$closedDate') } },
        {
            $group: {
                _id: '$weekIndex',
                weekIndex: { $first: '$weekIndex' },
                mergeCount: { $sum: 1 },
            },
        },
        { $sort: { weekIndex: 1 } },
        {
            $group: {
                _id: null,
                weekly: { $push: { weekIndex: '$weekIndex', mergeCount: '$mergeCount' } },
                average: { $avg: '$mergeCount' },
            },
        },
        { $project: { _id: 0 } },
    ]).then(result => result[0] || { weekly: [], average: 0 });
};
