"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
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 __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
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.FeatureFlagsService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const feature_flag_entity_1 = require("../entities/feature-flag.entity");
const tenant_flag_entity_1 = require("../entities/tenant-flag.entity");
const user_flag_entity_1 = require("../entities/user-flag.entity");
const crypto = __importStar(require("crypto"));
let FeatureFlagsService = class FeatureFlagsService {
    constructor(flagRepository, tenantFlagRepository, userFlagRepository) {
        this.flagRepository = flagRepository;
        this.tenantFlagRepository = tenantFlagRepository;
        this.userFlagRepository = userFlagRepository;
    }
    async createFlag(dto) {
        const existing = await this.flagRepository.findOne({
            where: { key: dto.key },
        });
        if (existing) {
            throw new common_1.ConflictException(`Flag with key '${dto.key}' already exists`);
        }
        const flag = this.flagRepository.create(dto);
        return this.flagRepository.save(flag);
    }
    async updateFlag(id, dto) {
        const flag = await this.flagRepository.findOne({ where: { id } });
        if (!flag) {
            throw new common_1.NotFoundException(`Flag with ID '${id}' not found`);
        }
        Object.assign(flag, dto);
        return this.flagRepository.save(flag);
    }
    async deleteFlag(id) {
        const flag = await this.flagRepository.findOne({ where: { id } });
        if (!flag) {
            throw new common_1.NotFoundException(`Flag with ID '${id}' not found`);
        }
        await this.flagRepository.remove(flag);
    }
    async getAllFlags() {
        return this.flagRepository.find({
            order: { category: 'ASC', key: 'ASC' },
        });
    }
    async getFlagByKey(key) {
        return this.flagRepository.findOne({ where: { key } });
    }
    async getFlagById(id) {
        return this.flagRepository.findOne({ where: { id } });
    }
    async toggleFlag(id, enabled) {
        const flag = await this.flagRepository.findOne({ where: { id } });
        if (!flag) {
            throw new common_1.NotFoundException(`Flag with ID '${id}' not found`);
        }
        flag.is_enabled = enabled;
        return this.flagRepository.save(flag);
    }
    async setTenantFlag(tenantId, dto) {
        const flag = await this.flagRepository.findOne({ where: { id: dto.flag_id } });
        if (!flag) {
            throw new common_1.NotFoundException(`Flag with ID '${dto.flag_id}' not found`);
        }
        let tenantFlag = await this.tenantFlagRepository.findOne({
            where: { tenant_id: tenantId, flag_id: dto.flag_id },
        });
        if (tenantFlag) {
            tenantFlag.is_enabled = dto.is_enabled ?? tenantFlag.is_enabled;
            tenantFlag.value = dto.value ?? tenantFlag.value;
            tenantFlag.metadata = dto.metadata ?? tenantFlag.metadata;
        }
        else {
            tenantFlag = this.tenantFlagRepository.create({
                tenant_id: tenantId,
                flag_id: dto.flag_id,
                is_enabled: dto.is_enabled ?? true,
                value: dto.value,
                metadata: dto.metadata,
            });
        }
        return this.tenantFlagRepository.save(tenantFlag);
    }
    async removeTenantFlag(tenantId, flagId) {
        const tenantFlag = await this.tenantFlagRepository.findOne({
            where: { tenant_id: tenantId, flag_id: flagId },
        });
        if (tenantFlag) {
            await this.tenantFlagRepository.remove(tenantFlag);
        }
    }
    async getTenantFlags(tenantId) {
        return this.tenantFlagRepository.find({
            where: { tenant_id: tenantId },
            relations: ['flag'],
        });
    }
    async setUserFlag(tenantId, dto) {
        const flag = await this.flagRepository.findOne({ where: { id: dto.flag_id } });
        if (!flag) {
            throw new common_1.NotFoundException(`Flag with ID '${dto.flag_id}' not found`);
        }
        let userFlag = await this.userFlagRepository.findOne({
            where: { user_id: dto.user_id, flag_id: dto.flag_id },
        });
        if (userFlag) {
            userFlag.is_enabled = dto.is_enabled ?? userFlag.is_enabled;
            userFlag.value = dto.value ?? userFlag.value;
            userFlag.metadata = dto.metadata ?? userFlag.metadata;
        }
        else {
            userFlag = this.userFlagRepository.create({
                tenant_id: tenantId,
                user_id: dto.user_id,
                flag_id: dto.flag_id,
                is_enabled: dto.is_enabled ?? true,
                value: dto.value,
                metadata: dto.metadata,
            });
        }
        return this.userFlagRepository.save(userFlag);
    }
    async removeUserFlag(userId, flagId) {
        const userFlag = await this.userFlagRepository.findOne({
            where: { user_id: userId, flag_id: flagId },
        });
        if (userFlag) {
            await this.userFlagRepository.remove(userFlag);
        }
    }
    async getUserFlags(tenantId, userId) {
        return this.userFlagRepository.find({
            where: { tenant_id: tenantId, user_id: userId },
            relations: ['flag'],
        });
    }
    async evaluateFlag(key, context) {
        const flag = await this.flagRepository.findOne({ where: { key } });
        if (!flag) {
            return {
                key,
                enabled: false,
                value: null,
                source: 'default',
            };
        }
        if (!flag.is_enabled) {
            return {
                key,
                enabled: false,
                value: flag.default_value,
                source: 'global',
            };
        }
        if (context.userId) {
            const userFlag = await this.userFlagRepository.findOne({
                where: { user_id: context.userId, flag_id: flag.id },
            });
            if (userFlag) {
                return {
                    key,
                    enabled: userFlag.is_enabled,
                    value: userFlag.value ?? flag.default_value,
                    source: 'user',
                };
            }
        }
        if (context.tenantId) {
            const tenantFlag = await this.tenantFlagRepository.findOne({
                where: { tenant_id: context.tenantId, flag_id: flag.id },
            });
            if (tenantFlag) {
                return {
                    key,
                    enabled: tenantFlag.is_enabled,
                    value: tenantFlag.value ?? flag.default_value,
                    source: 'tenant',
                };
            }
        }
        if (flag.rollout_percentage !== null && flag.rollout_percentage < 100) {
            const isInRollout = this.isInRollout(flag.rollout_percentage, context.userId || context.tenantId || 'anonymous', flag.key);
            return {
                key,
                enabled: isInRollout,
                value: isInRollout ? flag.default_value : null,
                source: 'rollout',
            };
        }
        return {
            key,
            enabled: flag.is_enabled,
            value: flag.default_value,
            source: 'global',
        };
    }
    async evaluateAllFlags(context) {
        const flags = await this.flagRepository.find();
        const evaluations = {};
        for (const flag of flags) {
            evaluations[flag.key] = await this.evaluateFlag(flag.key, context);
        }
        return evaluations;
    }
    async isEnabled(key, context) {
        const evaluation = await this.evaluateFlag(key, context);
        return evaluation.enabled;
    }
    async getValue(key, context, defaultValue) {
        const evaluation = await this.evaluateFlag(key, context);
        return evaluation.enabled ? (evaluation.value ?? defaultValue) : defaultValue;
    }
    isInRollout(percentage, identifier, flagKey) {
        const hash = crypto
            .createHash('md5')
            .update(`${flagKey}:${identifier}`)
            .digest('hex');
        const hashInt = parseInt(hash.substring(0, 8), 16);
        const normalized = hashInt / 0xffffffff;
        return normalized * 100 < percentage;
    }
};
exports.FeatureFlagsService = FeatureFlagsService;
exports.FeatureFlagsService = FeatureFlagsService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(feature_flag_entity_1.FeatureFlag)),
    __param(1, (0, typeorm_1.InjectRepository)(tenant_flag_entity_1.TenantFlag)),
    __param(2, (0, typeorm_1.InjectRepository)(user_flag_entity_1.UserFlag)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        typeorm_2.Repository,
        typeorm_2.Repository])
], FeatureFlagsService);
//# sourceMappingURL=feature-flags.service.js.map