import { z } from 'zod';
import { TeamModel } from './mongoose-models/TeamModel.js';
import { collectionAndProjectInputs } from './helpers.js';
export const createTeamInputParser = z.object({
    ...collectionAndProjectInputs,
    name: z.string(),
    repoIds: z.array(z.string()),
});
export const createTeam = async (team) => TeamModel.create(team).then(x => { var _a; return (_a = x._id) !== null && _a !== void 0 ? _a : null; });
export const deleteTeamInputParser = z.object({
    ...collectionAndProjectInputs,
    teamName: z.string(),
});
export const deleteTeam = async ({ collectionName, project, teamName, }) => TeamModel.deleteOne({ collectionName, project, name: teamName }).then(x => x.deletedCount);
export const updateTeamInputParser = z.object({
    ...collectionAndProjectInputs,
    oldName: z.string(),
    newName: z.string(),
    repoIds: z.array(z.string()),
});
export const updateTeam = async (team) => {
    const { collectionName, project, oldName, newName, repoIds } = team;
    return TeamModel.updateOne({ collectionName, project, name: oldName }, {
        collectionName,
        project,
        name: newName,
        repoIds,
    }, { upsert: true }).then(x => { var _a; return (_a = x.upsertedId) !== null && _a !== void 0 ? _a : null; });
};
export const getTeamNames = ({ collectionName, project, }) => TeamModel.find({
    collectionName,
    project,
}, { _id: 0, name: 1 }).then(x => x.map(y => y.name));
export const reposForTeamNameInputParser = z.object({
    ...collectionAndProjectInputs,
    name: z.string(),
});
export const getRepoIdsForTeamNames = (collectionName, project, teamNames) => {
    return TeamModel.aggregate([
        {
            $match: {
                collectionName,
                project,
                name: { $in: teamNames },
            },
        },
        {
            $unwind: {
                path: '$repoIds',
                preserveNullAndEmptyArrays: false,
            },
        },
        { $addFields: { repoId: '$repoIds' } },
        {
            $group: {
                _id: null,
                repoIds: { $addToSet: '$repoId' },
            },
        },
        { $project: { _id: 0 } },
    ]).then(x => { var _a, _b; return (_b = (_a = x[0]) === null || _a === void 0 ? void 0 : _a.repoIds) !== null && _b !== void 0 ? _b : []; });
};
export const getRepoIdsForTeamName = ({ collectionName, project, name, }) => {
    return getRepoIdsForTeamNames(collectionName, project, [name]);
};
