"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); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var SolidMicroserviceAdapter_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SolidMicroserviceAdapter = void 0;
const cache_manager_1 = require("@nestjs/cache-manager");
const common_1 = require("@nestjs/common");
const axios_1 = __importDefault(require("axios"));
let SolidMicroserviceAdapter = SolidMicroserviceAdapter_1 = class SolidMicroserviceAdapter {
    constructor(cacheManager) {
        this.cacheManager = cacheManager;
        this.logger = new common_1.Logger(SolidMicroserviceAdapter_1.name);
    }
    setBaseUrl(baseUrl) {
        this.baseUrl = baseUrl;
        return this;
    }
    async authenticate({ email, username, password }) {
        if (!password) {
            throw new Error('password is required for IAM authentication');
        }
        if (!email && !username) {
            throw new Error('email or username is required for IAM authentication');
        }
        const cacheKey = this.getAuthCacheKey(email, username);
        const cachedResponse = (await this.cacheManager.get(cacheKey));
        if (cachedResponse) {
            this.logger.debug(`IAM auth cache hit for ${cacheKey}`);
            return cachedResponse;
        }
        this.logger.debug(`IAM auth cache miss for ${cacheKey}`);
        if (!this.baseUrl) {
            throw new Error('baseUrl must be set before IAM authentication');
        }
        const payload = { password };
        if (email)
            payload.email = email;
        if (username)
            payload.username = username;
        this.logger.debug(`Requesting IAM access token from ${this.baseUrl}/api/iam/authenticate`);
        const response = await axios_1.default.post(`${this.baseUrl}/api/iam/authenticate`, payload, {
            timeout: 10000,
            headers: {
                'Content-Type': 'application/json',
            },
        });
        const responseData = response.data;
        const ttlSeconds = this.getJwtTtlSeconds(responseData?.data?.accessToken);
        if (ttlSeconds && ttlSeconds > 0) {
            await this.cacheManager.set(cacheKey, responseData, ttlSeconds);
        }
        return responseData;
    }
    getAuthCacheKey(email, username) {
        return `iam-auth:${email ?? ''}:${username ?? ''}`;
    }
    getJwtTtlSeconds(accessToken) {
        if (!accessToken)
            return undefined;
        const parts = accessToken.split('.');
        if (parts.length < 2)
            return undefined;
        try {
            const payloadJson = Buffer.from(this.base64UrlToBase64(parts[1]), 'base64').toString('utf-8');
            const payload = JSON.parse(payloadJson);
            if (!payload?.exp || typeof payload.exp !== 'number')
                return undefined;
            const nowSeconds = Math.floor(Date.now() / 1000);
            const ttl = payload.exp - nowSeconds - 10;
            return ttl > 0 ? ttl : undefined;
        }
        catch {
            return undefined;
        }
    }
    base64UrlToBase64(value) {
        const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
        const padLength = (4 - (normalized.length % 4)) % 4;
        return normalized + '='.repeat(padLength);
    }
};
exports.SolidMicroserviceAdapter = SolidMicroserviceAdapter;
exports.SolidMicroserviceAdapter = SolidMicroserviceAdapter = SolidMicroserviceAdapter_1 = __decorate([
    (0, common_1.Injectable)({ scope: common_1.Scope.TRANSIENT }),
    __param(0, (0, common_1.Inject)(cache_manager_1.CACHE_MANAGER)),
    __metadata("design:paramtypes", [Object])
], SolidMicroserviceAdapter);
//# sourceMappingURL=solid-microservice-adapter.service.js.map