"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 ApiKeyService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiKeyService = void 0;
const common_1 = require("@nestjs/common");
const crypto_1 = require("crypto");
const error_messages_1 = require("../constants/error-messages");
const user_api_key_entity_1 = require("../entities/user-api-key.entity");
const user_entity_1 = require("../entities/user.entity");
const user_api_key_repository_1 = require("../repository/user-api-key.repository");
const permission_metadata_service_1 = require("./permission-metadata.service");
const authentication_service_1 = require("./authentication.service");
const user_repository_1 = require("../repository/user.repository");
let ApiKeyService = ApiKeyService_1 = class ApiKeyService {
    constructor(apiKeyRepository, permissionMetadataService, authenticationService, userRepository) {
        this.apiKeyRepository = apiKeyRepository;
        this.permissionMetadataService = permissionMetadataService;
        this.authenticationService = authenticationService;
        this.userRepository = userRepository;
        this.logger = new common_1.Logger(ApiKeyService_1.name);
    }
    async generate(userId, dto) {
        const user = await this.apiKeyRepository.manager.findOne(user_entity_1.User, {
            where: { id: userId },
            select: ['id', 'isAllowedToGenerateApiKeys'],
        });
        if (!user?.isAllowedToGenerateApiKeys) {
            throw new common_1.ForbiddenException('You are not allowed to generate API keys');
        }
        const rawKey = 'sldx_' + (0, crypto_1.randomBytes)(32).toString('hex');
        const hashedKey = this.hash(rawKey);
        const maskedKey = 'sldx_****' + rawKey.slice(-4);
        const record = this.apiKeyRepository.create({
            name: dto.name,
            hashedKey,
            maskedKey,
            isActive: true,
            expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : null,
            user,
        });
        await this.apiKeyRepository.save(record);
        delete record.hashedKey;
        return { apiKey: rawKey, record };
    }
    async validate(rawKey) {
        const hashedKey = this.hash(rawKey);
        const keyRecord = await this.apiKeyRepository.findOne({
            where: { hashedKey, isActive: true },
            relations: ['user', 'user.roles'],
        });
        if (!keyRecord) {
            throw new common_1.UnauthorizedException();
        }
        if (keyRecord.expiresAt && keyRecord.expiresAt < new Date()) {
            throw new common_1.UnauthorizedException('API key expired');
        }
        this.apiKeyRepository.update(keyRecord.id, { lastUsedAt: new Date() }).catch((err) => {
            this.logger.warn(`Failed to update lastUsedAt for key ${keyRecord.id}: ${err.message}`);
        });
        const roles = (keyRecord.user.roles ?? []).map((r) => r.name);
        const permissions = await this.permissionMetadataService.findAllUsingRoles(roles);
        return {
            sub: keyRecord.user.id,
            username: keyRecord.user.username,
            email: keyRecord.user.email,
            roles,
            permissions: permissions.map((p) => p.name),
        };
    }
    async updateKey(id, userId, dto) {
        const keyRecord = await this.apiKeyRepository.findOne({
            where: { id, user: { id: userId } },
        });
        if (!keyRecord) {
            throw new common_1.NotFoundException('API key not found');
        }
        await this.apiKeyRepository.manager
            .createQueryBuilder()
            .update(user_api_key_entity_1.UserApiKey)
            .set({ isActive: dto.isActive })
            .where('id = :id', { id })
            .execute();
    }
    async apiKeyMe(apiKey) {
        const hasedKey = this.hash(apiKey);
        const apiKeyRecord = await this.apiKeyRepository.findOne({
            where: {
                hashedKey: hasedKey,
            },
            relations: {
                user: {
                    roles: true
                }
            }
        });
        if (!apiKeyRecord) {
            throw new common_1.UnauthorizedException(error_messages_1.ERROR_MESSAGES.INVALID_CREDENTIALS);
        }
        const user = apiKeyRecord.user;
        const tokens = await this.authenticationService.generateTokens(user);
        return {
            user: {
                email: user.email,
                mobile: user.mobile,
                username: user.username,
                forcePasswordChange: user.forcePasswordChange,
                id: user.id,
                roles: user.roles.map((role) => role.name)
            },
            ...tokens
        };
    }
    hash(rawKey) {
        return (0, crypto_1.createHash)('sha256').update(rawKey).digest('hex');
    }
};
exports.ApiKeyService = ApiKeyService;
exports.ApiKeyService = ApiKeyService = ApiKeyService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [user_api_key_repository_1.UserApiKeyRepository,
        permission_metadata_service_1.PermissionMetadataService,
        authentication_service_1.AuthenticationService,
        user_repository_1.UserRepository])
], ApiKeyService);
//# sourceMappingURL=api-key.service.js.map