import pluralize from 'pluralize';
import { asc, byNum } from 'sort-lib';
import { prop } from 'rambda';
import { exists } from '../../shared/utils.js';
import { configForCollection } from '../config.js';
import workItemIconSvgs from '../work-item-icon-svgs.js';
import { WorkItemTypeModel } from './mongoose-models/WorkItemType.js';
import { getProjectConfig } from './config.js';
const iconSvg = ({ id, url }) => {
    const { searchParams } = new URL(url);
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    return workItemIconSvgs[id](searchParams.get('color'));
};
export const getWorkItemConfig = async ({ collectionName, project, }) => {
    var _a, _b;
    const config = await getProjectConfig(collectionName, project);
    const workItemTypes = await WorkItemTypeModel.find({
        collectionName,
        project,
        name: { $in: (_a = config.workItemsConfig) === null || _a === void 0 ? void 0 : _a.map(w => w.type) },
    }).lean();
    return {
        environments: config.environments,
        workItemsConfig: (_b = config.workItemsConfig) === null || _b === void 0 ? void 0 : _b.map(workItemConfig => {
            const match = workItemTypes.find(wit => wit.name === workItemConfig.type);
            if (!match)
                return;
            const fieldName = (fieldId) => {
                const fieldDetails = match.fields.find(f => f.referenceName === fieldId);
                if (!fieldDetails)
                    return;
                return [fieldDetails.referenceName, fieldDetails.name];
            };
            const fieldNames = (fieldIds) => {
                return Object.fromEntries(fieldIds.map(fieldName).filter(exists));
            };
            return {
                name: [match.name, pluralize(match.name)],
                icon: `data:image/svg+xml;utf8,${encodeURIComponent(iconSvg(match.icon))}`,
                groupByField: workItemConfig.groupByField
                    ? fieldNames([workItemConfig.groupByField])
                    : undefined,
                startStates: workItemConfig.startStates,
                endStates: workItemConfig.endStates,
                devCompleteStates: workItemConfig.devCompletionStates,
                rootCause: workItemConfig.rootCause && fieldNames(workItemConfig.rootCause),
                ignoreStates: workItemConfig.ignoreStates,
                workCenters: workItemConfig.workCenters,
            };
        }).filter(exists),
    };
};
export const getWorkItemTypes = async ({ collectionName, project, }) => {
    const collectionConfig = configForCollection(collectionName);
    const wits = (collectionConfig === null || collectionConfig === void 0 ? void 0 : collectionConfig.workitems.types) || [];
    // TODO: FIXME This doesn't belong here, maybe?
    const workItemTypes = await WorkItemTypeModel.find({
        collectionName,
        project,
        referenceName: { $in: wits.map(t => t.type) },
    }, { name: 1, icon: 1, fields: 1 }).lean();
    return (workItemTypes
        // Sort by the sequence of work item types in the config
        .sort(asc(byNum(wit => wits.map(prop('type')).indexOf(wit.name))))
        .map(wit => {
        var _a, _b;
        const matchingWitConfig = wits.find(w => w.type === wit.name);
        const fields = (fieldNames) => fieldNames === null || fieldNames === void 0 ? void 0 : fieldNames.map(field => { var _a; return (_a = wit.fields.find(f => f.referenceName === field)) === null || _a === void 0 ? void 0 : _a.name; }).filter(exists);
        return {
            name: [wit.name, pluralize(wit.name)],
            icon: `data:image/svg+xml;utf8,${encodeURIComponent(iconSvg(wit.icon))}`,
            startDateFields: fields(matchingWitConfig === null || matchingWitConfig === void 0 ? void 0 : matchingWitConfig.startDate),
            endDateFields: fields(matchingWitConfig === null || matchingWitConfig === void 0 ? void 0 : matchingWitConfig.endDate),
            devCompleteFields: fields(matchingWitConfig === null || matchingWitConfig === void 0 ? void 0 : matchingWitConfig.devCompletionDate),
            groupLabel: (_a = matchingWitConfig === null || matchingWitConfig === void 0 ? void 0 : matchingWitConfig.groupLabel) !== null && _a !== void 0 ? _a : ((matchingWitConfig === null || matchingWitConfig === void 0 ? void 0 : matchingWitConfig.groupByField)
                ? (_b = fields([matchingWitConfig.groupByField])) === null || _b === void 0 ? void 0 : _b[0]
                : undefined),
            workCenters: ((matchingWitConfig === null || matchingWitConfig === void 0 ? void 0 : matchingWitConfig.workCenters) || []).map(wc => ({
                label: wc.label,
                startDateFields: fields(wc.startDate),
                endDateFields: fields(wc.endDate),
            })),
            rootCauseFields: fields(matchingWitConfig === null || matchingWitConfig === void 0 ? void 0 : matchingWitConfig.rootCause),
        };
    }));
};
