"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkUserPasswordExpiration = void 0;
var tslib_1 = require("tslib");
var moment = require('moment');
var checkUserPasswordExpiration = function (ctx) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var today, advanceNoticeDays, processedUserIds, spaces, spaces_1, spaces_1_1, space, expirationDays, checks, checks_1, checks_1_1, check, targetDateStart, targetDateEnd, expiredUsers, expiredUsers_1, expiredUsers_1_1, user, emailSubject, emailBody, err_1, e_1_1, e_2_1, e_3_1, e_4;
    var e_3, _a, e_2, _b, e_1, _c;
    return tslib_1.__generator(this, function (_d) {
        switch (_d.label) {
            case 0:
                _d.trys.push([0, 25, , 26]);
                today = new Date();
                advanceNoticeDays = parseInt(process.env.PEPSICO_PASSWORD_EXPIRY_ADVANCE_DAYS || '5');
                processedUserIds = new Set();
                return [4, ctx.getObject('spaces').find({
                        filters: [['password_expiration_days', '>', 0]],
                        fields: ['_id', 'name', 'password_expiration_days']
                    })];
            case 1:
                spaces = _d.sent();
                _d.label = 2;
            case 2:
                _d.trys.push([2, 22, 23, 24]);
                spaces_1 = tslib_1.__values(spaces), spaces_1_1 = spaces_1.next();
                _d.label = 3;
            case 3:
                if (!!spaces_1_1.done) return [3, 21];
                space = spaces_1_1.value;
                expirationDays = space.password_expiration_days;
                checks = [
                    { type: 'expired', daysOffset: expirationDays },
                ];
                if (advanceNoticeDays > 0 && advanceNoticeDays < expirationDays) {
                    checks.push({ type: 'warning', daysOffset: expirationDays - advanceNoticeDays });
                }
                _d.label = 4;
            case 4:
                _d.trys.push([4, 18, 19, 20]);
                checks_1 = (e_2 = void 0, tslib_1.__values(checks)), checks_1_1 = checks_1.next();
                _d.label = 5;
            case 5:
                if (!!checks_1_1.done) return [3, 17];
                check = checks_1_1.value;
                targetDateStart = moment().subtract(check.daysOffset, 'days').startOf('day').toDate();
                targetDateEnd = moment().subtract(check.daysOffset, 'days').endOf('day').toDate();
                console.log("[PasswordExpiry] Checking space '".concat(space.name, "' (expiration: ").concat(expirationDays, " days, type: ").concat(check.type, "). Looking for passwords modified between ").concat(targetDateStart, " and ").concat(targetDateEnd));
                return [4, ctx.getObject('users').find({
                        filters: [
                            ['password_modified_date', '>=', targetDateStart],
                            ['password_modified_date', '<=', targetDateEnd],
                            ['is_valid', '=', true],
                            ['email', '!=', null]
                        ],
                        fields: ['_id', 'name', 'email', 'password_modified_date']
                    })];
            case 6:
                expiredUsers = _d.sent();
                console.log("[PasswordExpiry] Found ".concat(expiredUsers.length, " users to notify in space ").concat(space.name, " for ").concat(check.type));
                _d.label = 7;
            case 7:
                _d.trys.push([7, 14, 15, 16]);
                expiredUsers_1 = (e_1 = void 0, tslib_1.__values(expiredUsers)), expiredUsers_1_1 = expiredUsers_1.next();
                _d.label = 8;
            case 8:
                if (!!expiredUsers_1_1.done) return [3, 13];
                user = expiredUsers_1_1.value;
                if (processedUserIds.has(user._id)) {
                    return [3, 12];
                }
                _d.label = 9;
            case 9:
                _d.trys.push([9, 11, , 12]);
                emailSubject = '';
                emailBody = '';
                if (check.type === 'expired') {
                    emailSubject = "\u60A8\u7684\u5BC6\u7801\u5DF2\u8FC7\u671F - ".concat(space.name);
                    emailBody = "\n                                <p>\u5C0A\u656C\u7684 ".concat(user.name, ":</p>\n                                <p>\u6839\u636E ").concat(space.name, " \u7684\u5B89\u5168\u7B56\u7565\uFF0C\u7528\u6237\u7684\u5BC6\u7801\u6709\u6548\u671F\u4E3A ").concat(expirationDays, " \u5929\u3002</p>\n                                <p>\u60A8\u7684\u5BC6\u7801\u6700\u540E\u4FEE\u6539\u4E8E ").concat(moment(user.password_modified_date).format('YYYY-MM-DD'), "\uFF0C\u76EE\u524D\u5DF2\u7ECF\u8FC7\u671F\u3002</p>\n                                <p>\u8BF7\u5C3D\u5FEB\u767B\u5F55\u7CFB\u7EDF\u5E76\u4FEE\u6539\u60A8\u7684\u5BC6\u7801\u3002</p>\n                                <br/>\n                                <p>\u7CFB\u7EDF\u81EA\u52A8\u53D1\u9001\uFF0C\u8BF7\u52FF\u56DE\u590D\u3002</p>\n                            ");
                }
                else {
                    emailSubject = "\u60A8\u7684\u5BC6\u7801\u5373\u5C06\u8FC7\u671F - ".concat(space.name);
                    emailBody = "\n                                <p>\u5C0A\u656C\u7684 ".concat(user.name, ":</p>\n                                <p>\u6839\u636E ").concat(space.name, " \u7684\u5B89\u5168\u7B56\u7565\uFF0C\u7528\u6237\u7684\u5BC6\u7801\u6709\u6548\u671F\u4E3A ").concat(expirationDays, " \u5929\u3002</p>\n                                <p>\u60A8\u7684\u5BC6\u7801\u6700\u540E\u4FEE\u6539\u4E8E ").concat(moment(user.password_modified_date).format('YYYY-MM-DD'), "\uFF0C\u5C06\u4E8E ").concat(advanceNoticeDays, " \u5929\u540E\u8FC7\u671F\u3002</p>\n                                <p>\u8BF7\u5C3D\u5FEB\u767B\u5F55\u7CFB\u7EDF\u5E76\u4FEE\u6539\u60A8\u7684\u5BC6\u7801\u3002</p>\n                                <br/>\n                                <p>\u7CFB\u7EDF\u81EA\u52A8\u53D1\u9001\uFF0C\u8BF7\u52FF\u56DE\u590D\u3002</p>\n                            ");
                }
                return [4, ctx.broker.call('@builder6/email.send', {
                        to: user.email,
                        subject: emailSubject,
                        html: emailBody
                    })];
            case 10:
                _d.sent();
                console.log("[PasswordExpiry] Email sent to ".concat(user.email, " (").concat(user._id, ") - ").concat(check.type));
                processedUserIds.add(user._id);
                return [3, 12];
            case 11:
                err_1 = _d.sent();
                console.error("[PasswordExpiry] Failed to send email to ".concat(user.email, ":"), err_1);
                processedUserIds.add(user._id);
                return [3, 12];
            case 12:
                expiredUsers_1_1 = expiredUsers_1.next();
                return [3, 8];
            case 13: return [3, 16];
            case 14:
                e_1_1 = _d.sent();
                e_1 = { error: e_1_1 };
                return [3, 16];
            case 15:
                try {
                    if (expiredUsers_1_1 && !expiredUsers_1_1.done && (_c = expiredUsers_1.return)) _c.call(expiredUsers_1);
                }
                finally { if (e_1) throw e_1.error; }
                return [7];
            case 16:
                checks_1_1 = checks_1.next();
                return [3, 5];
            case 17: return [3, 20];
            case 18:
                e_2_1 = _d.sent();
                e_2 = { error: e_2_1 };
                return [3, 20];
            case 19:
                try {
                    if (checks_1_1 && !checks_1_1.done && (_b = checks_1.return)) _b.call(checks_1);
                }
                finally { if (e_2) throw e_2.error; }
                return [7];
            case 20:
                spaces_1_1 = spaces_1.next();
                return [3, 3];
            case 21: return [3, 24];
            case 22:
                e_3_1 = _d.sent();
                e_3 = { error: e_3_1 };
                return [3, 24];
            case 23:
                try {
                    if (spaces_1_1 && !spaces_1_1.done && (_a = spaces_1.return)) _a.call(spaces_1);
                }
                finally { if (e_3) throw e_3.error; }
                return [7];
            case 24: return [3, 26];
            case 25:
                e_4 = _d.sent();
                console.error("[PasswordExpiry] Error:", e_4);
                return [3, 26];
            case 26: return [2];
        }
    });
}); };
exports.checkUserPasswordExpiration = checkUserPasswordExpiration;
//# sourceMappingURL=password_expiry.js.map