"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.migrateSpotCheckDepartments = void 0;
var tslib_1 = require("tslib");
var objectql = require("@steedos/objectql");
function getCollection(name) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var adapter;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    adapter = objectql.getDataSource('default').adapter;
                    return [4, adapter.connect()];
                case 1:
                    _a.sent();
                    return [2, adapter.collection(name)];
            }
        });
    });
}
exports.migrateSpotCheckDepartments = {
    rest: {
        method: 'GET',
        fullPath: '/api/pepsico-content/material/migrate-spot-check-departments'
    },
    handler: function (ctx) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var user, logger, materialCol, spaceUsersCol, materials, updated, skipped, errors, materials_1, materials_1_1, material, spaceUser, departments, error_1, e_1_1, error_2;
            var e_1, _a;
            return tslib_1.__generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        user = ctx.meta.user;
                        ctx.getObject = this.getObject;
                        return [4, this.getLogger()];
                    case 1:
                        logger = _b.sent();
                        ctx.logger = logger;
                        if (!user || !user.is_space_admin) {
                            return [2, {
                                    status: 403,
                                    msg: "只有管理员可以执行数据迁移",
                                    data: {}
                                }];
                        }
                        _b.label = 2;
                    case 2:
                        _b.trys.push([2, 17, , 18]);
                        return [4, getCollection('pepsico_material')];
                    case 3:
                        materialCol = _b.sent();
                        return [4, getCollection('space_users')];
                    case 4:
                        spaceUsersCol = _b.sent();
                        return [4, materialCol.find({
                                pepsico_spot_check: { $ne: null },
                                $or: [
                                    { spot_check_departments: { $exists: false } },
                                    { spot_check_departments: null },
                                    { spot_check_departments: { $size: 0 } }
                                ]
                            }, { projection: { _id: 1, pepsico_spot_check: 1, space: 1 } }).toArray()];
                    case 5:
                        materials = _b.sent();
                        logger === null || logger === void 0 ? void 0 : logger.info("Found ".concat(materials.length, " materials with missing spot_check_departments"));
                        updated = 0;
                        skipped = 0;
                        errors = [];
                        _b.label = 6;
                    case 6:
                        _b.trys.push([6, 14, 15, 16]);
                        materials_1 = tslib_1.__values(materials), materials_1_1 = materials_1.next();
                        _b.label = 7;
                    case 7:
                        if (!!materials_1_1.done) return [3, 13];
                        material = materials_1_1.value;
                        _b.label = 8;
                    case 8:
                        _b.trys.push([8, 11, , 12]);
                        return [4, spaceUsersCol.findOne({ user: material.pepsico_spot_check, space: material.space })];
                    case 9:
                        spaceUser = _b.sent();
                        if (!(spaceUser === null || spaceUser === void 0 ? void 0 : spaceUser.organization)) {
                            logger === null || logger === void 0 ? void 0 : logger.warn("No organization found for user ".concat(material.pepsico_spot_check, ", material ").concat(material._id));
                            skipped++;
                            return [3, 12];
                        }
                        departments = [spaceUser.organization];
                        return [4, materialCol.updateOne({ _id: material._id }, { $set: { spot_check_departments: departments } })];
                    case 10:
                        _b.sent();
                        updated++;
                        if (updated % 100 === 0) {
                            logger === null || logger === void 0 ? void 0 : logger.info("Updated ".concat(updated, " records..."));
                        }
                        return [3, 12];
                    case 11:
                        error_1 = _b.sent();
                        logger === null || logger === void 0 ? void 0 : logger.error("Error processing material ".concat(material._id), error_1);
                        errors.push(material._id);
                        return [3, 12];
                    case 12:
                        materials_1_1 = materials_1.next();
                        return [3, 7];
                    case 13: return [3, 16];
                    case 14:
                        e_1_1 = _b.sent();
                        e_1 = { error: e_1_1 };
                        return [3, 16];
                    case 15:
                        try {
                            if (materials_1_1 && !materials_1_1.done && (_a = materials_1.return)) _a.call(materials_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                        return [7];
                    case 16:
                        logger === null || logger === void 0 ? void 0 : logger.info("Migration complete. Updated: ".concat(updated, ", Skipped: ").concat(skipped, ", Errors: ").concat(errors.length));
                        return [2, {
                                status: 0,
                                msg: "spot_check_departments 数据修正完成",
                                data: {
                                    updated: updated,
                                    skipped: skipped,
                                    errors: errors.length,
                                    total: materials.length
                                }
                            }];
                    case 17:
                        error_2 = _b.sent();
                        logger === null || logger === void 0 ? void 0 : logger.error('Migration failed', error_2);
                        return [2, {
                                status: 500,
                                msg: "\u6570\u636E\u4FEE\u6B63\u5931\u8D25: ".concat(error_2.message),
                                data: {}
                            }];
                    case 18: return [2];
                }
            });
        });
    }
};
//# sourceMappingURL=migrateSpotCheckDepartments.js.map