"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdminUserManagementService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const tenant_service_1 = require("../../tenant/services/tenant.service");
const auth_config_service_1 = require("../../core/services/auth-config.service");
const user_access_entity_1 = require("../../user/entities/user-access.entity");
const nest_auth_contracts_1 = require("@ackplus/nest-auth-contracts");
let AdminUserManagementService = class AdminUserManagementService {
    userAccessRepository;
    tenantService;
    authConfigService;
    constructor(userAccessRepository, tenantService, authConfigService) {
        this.userAccessRepository = userAccessRepository;
        this.tenantService = tenantService;
        this.authConfigService = authConfigService;
    }
    getTenantMode() {
        const config = this.authConfigService.getConfig();
        const mode = config.tenant?.mode;
        return mode === nest_auth_contracts_1.TenantModeEnum.SHARED ? nest_auth_contracts_1.TenantModeEnum.SHARED : nest_auth_contracts_1.TenantModeEnum.ISOLATED;
    }
    async ensureUserAccess(userId, tenantId) {
        if (!userId || !tenantId) {
            return null;
        }
        const existing = await this.userAccessRepository.findOne({
            where: { userId, tenantId },
        });
        if (existing) {
            if (!existing.isActive) {
                existing.isActive = true;
                await this.userAccessRepository.save(existing);
            }
            return existing;
        }
        const access = this.userAccessRepository.create({
            userId,
            tenantId,
        });
        return await this.userAccessRepository.save(access);
    }
    async syncUserAccesses(userId, tenantIds) {
        if (!userId) {
            return [];
        }
        const tenantMode = this.getTenantMode();
        if (tenantMode === nest_auth_contracts_1.TenantModeEnum.ISOLATED) {
            if (tenantIds?.length) {
                const resolvedTenantId = await this.tenantService.resolveTenantId(tenantIds[0]);
                if (resolvedTenantId) {
                    const existing = await this.userAccessRepository.find({ where: { userId } });
                    const toDeactivate = existing.filter((a) => a.tenantId !== resolvedTenantId && a.isActive);
                    if (toDeactivate.length) {
                        toDeactivate.forEach((a) => { a.isActive = false; });
                        await this.userAccessRepository.save(toDeactivate);
                    }
                    await this.ensureUserAccess(userId, resolvedTenantId);
                    return this.userAccessRepository.find({
                        where: { userId, isActive: true },
                        relations: ['tenant'],
                    });
                }
            }
            return [];
        }
        const resolvedTenantIds = (await Promise.all((tenantIds || [])
            .map((id) => (id ? id.trim() : ''))
            .filter(Boolean)
            .map((id) => this.tenantService.resolveTenantId(id)))).filter(Boolean);
        if (resolvedTenantIds.length === 0) {
            const existingList = await this.userAccessRepository.find({ where: { userId } });
            const updates = existingList
                .filter((a) => a.isActive)
                .map((a) => {
                a.isActive = false;
                return a;
            });
            if (updates.length) {
                await this.userAccessRepository.save(updates);
            }
            return [];
        }
        const existingList = await this.userAccessRepository.find({ where: { userId } });
        const accessByTenant = new Map(existingList.map((a) => [a.tenantId, a]));
        const tenantIdSet = new Set(resolvedTenantIds);
        const updates = [];
        for (const access of existingList) {
            const shouldBeActive = tenantIdSet.has(access.tenantId);
            if (access.isActive !== shouldBeActive) {
                access.isActive = shouldBeActive;
                updates.push(access);
            }
        }
        for (const tenantId of resolvedTenantIds) {
            if (!accessByTenant.has(tenantId)) {
                updates.push(this.userAccessRepository.create({
                    userId,
                    tenantId,
                    isActive: true,
                }));
            }
        }
        if (updates.length) {
            await this.userAccessRepository.save(updates);
        }
        return this.userAccessRepository.find({
            where: { userId, isActive: true },
            relations: ['tenant'],
        });
    }
};
exports.AdminUserManagementService = AdminUserManagementService;
exports.AdminUserManagementService = AdminUserManagementService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(user_access_entity_1.NestAuthUserAccess)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        tenant_service_1.TenantService,
        auth_config_service_1.AuthConfigService])
], AdminUserManagementService);
//# sourceMappingURL=admin-user-management.service.js.map