"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GroupsService = void 0;
const groups_db_1 = require("../db/groups.db");
const MappedGroup_model_1 = __importDefault(require("../models/MappedGroup.model"));
class GroupsService {
    async createBorrowerGroups(borrowerId, groupType, groups) {
        const groupIds = groups.map((group) => group._id);
        const allExistedGroups = await groups_db_1.groupsMap[groupType].Model.find({ borrowerId }).lean();
        await Promise.all(allExistedGroups.map(async (group) => {
            if (!groupIds.includes(group._id.toString())) {
                await groups_db_1.groupsMap[groupType].Model.findByIdAndDelete(group._id.toString());
            }
        }));
        await Promise.all(groups.map(async (group) => {
            if (!group._id) {
                const newGroup = new groups_db_1.groupsMap[groupType].Model(group);
                await newGroup.save();
            }
            else {
                await groups_db_1.groupsMap[groupType].Model.findByIdAndUpdate(group._id, group);
            }
        }));
    }
    async getBorrowerGroups(borrowerId, relationshipGroups) {
        if (typeof relationshipGroups == 'string') {
            relationshipGroups = [relationshipGroups];
        }
        const allCustomerGroups = await Promise.all(relationshipGroups.map(async (groupName) => {
            const groups = await groups_db_1.groupsMap[groupName].Model.find({ borrowerId }).sort({ 'createdAt': 1 });
            return { [groupName]: groups };
        }));
        return allCustomerGroups.reduce((acc, group) => {
            return { ...acc, ...group };
        }, {});
    }
    async createMappedGroups(borrowerId, groupType, groups) {
        await MappedGroup_model_1.default.deleteMany({ borrowerId, groupType });
        await Promise.all(groups.map(async (group) => {
            const newMappedGroup = new MappedGroup_model_1.default({
                borrowerId,
                group1: group.group1,
                group2: group.group2,
                groupType: groupType,
            });
            await newMappedGroup.save();
        }));
    }
    async getMappedGroups(borrowerId, groupTypes) {
        if (typeof groupTypes == 'string') {
            groupTypes = [groupTypes];
        }
        const allMappedGroups = await Promise.all(groupTypes.map(async (groupType) => {
            const groups = await MappedGroup_model_1.default.find({ borrowerId, groupType });
            return { [groupType]: groups };
        }));
        return allMappedGroups.reduce((acc, group) => {
            return { ...acc, ...group };
        }, {});
    }
}
exports.GroupsService = GroupsService;
