import pMemoize from 'p-memoize';
import ExpiryMap from 'expiry-map';
import { z } from 'zod';
import { ConfigModel } from './mongoose-models/ConfigModel.js';
import { oneSecondInMs } from '../../shared/utils.js';
import { collectionAndProjectInputs } from './helpers.js';
const getGlobalConfig = () => ConfigModel.findOne({
    collectionName: null,
    project: null,
}).lean();
const getCollectionConfig = (collectionName) => ConfigModel.findOne({
    collectionName,
    project: null,
}).lean();
const cache = new ExpiryMap(10 * oneSecondInMs);
export const getProjectConfig = pMemoize(async (collectionName, projectName) => {
    var _a, _b;
    const [globalConfig, collectionConfig, projectConfig] = await Promise.all([
        getGlobalConfig(),
        getCollectionConfig(collectionName),
        ConfigModel.findOne({
            collectionName,
            project: projectName,
        }).lean(),
    ]);
    const merged = {
        ...globalConfig,
        ...collectionConfig,
        ...projectConfig,
    };
    return {
        ...merged,
        filterWorkItemsBy: (_a = merged.filterWorkItemsBy) === null || _a === void 0 ? void 0 : _a.map(f => ({ ...f })),
        workItemsConfig: (_b = merged.workItemsConfig) === null || _b === void 0 ? void 0 : _b.map(wic => {
            return {
                ...wic,
                startStates: wic.startStates || ['New'],
                endStates: wic.endStates || ['Closed'],
            };
        }),
    };
}, { cache, cacheKey: args => args.join('::') });
export const updateProjectConfigInputParser = z.object({
    ...collectionAndProjectInputs,
    config: z.array(z.object({
        type: z.string(),
        startStates: z.array(z.string()),
        endStates: z.array(z.string()),
        groupByField: z.string().optional(),
        rootCause: z.array(z.string()).optional(),
        ignoreStates: z.array(z.string()).optional(),
        workCenters: z
            .array(z.object({
            label: z.string(),
            startStates: z.array(z.string()).optional(),
            endStates: z.array(z.string()).optional(),
        }))
            .optional(),
        devCompletionStates: z.array(z.string()).optional(),
    })),
});
export const updateProjectConfig = ({ collectionName, project, config, }) => {
    return ConfigModel.findOneAndUpdate({ collectionName, project }, { $set: { collectionName, project, workItemsConfig: config } }, { upsert: true });
};
