"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 AdminConsoleController_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdminConsoleController = void 0;
const common_1 = require("@nestjs/common");
const path_1 = require("path");
const fs_1 = require("fs");
const admin_console_config_service_1 = require("../services/admin-console-config.service");
const candidateStaticRoots = [
    (0, path_1.join)(__dirname, '..', 'static'),
    (0, path_1.join)(process.cwd(), 'packages', 'nest-auth', 'src', 'lib', 'admin-console', 'static'),
    (0, path_1.join)(process.cwd(), 'dist', 'apps', 'nest-examples', 'packages', 'nest-auth', 'src', 'lib', 'admin-console', 'static'),
    (0, path_1.join)(process.cwd(), 'dist', 'packages', 'nest-auth', 'src', 'lib', 'admin-console', 'static'),
];
function resolveStaticRoot() {
    for (const root of candidateStaticRoots) {
        if ((0, fs_1.existsSync)((0, path_1.join)(root, 'index.html'))) {
            return root;
        }
    }
    return candidateStaticRoots[1];
}
let AdminConsoleController = AdminConsoleController_1 = class AdminConsoleController {
    config;
    logger = new common_1.Logger(AdminConsoleController_1.name);
    cachedIndexHtml = null;
    staticRoot = resolveStaticRoot();
    indexPath = (0, path_1.join)(this.staticRoot, 'index.html');
    constructor(config) {
        this.config = config;
    }
    onModuleInit() {
        if (this.config.getConfig().enabled === false) {
            return;
        }
        if (!(0, fs_1.existsSync)(this.indexPath)) {
            this.logger.error('Admin console index.html not found at startup', { path: this.indexPath });
            throw new Error(`Admin console index.html not found at ${this.indexPath}`);
        }
        try {
            this.cachedIndexHtml = (0, fs_1.readFileSync)(this.indexPath, 'utf8');
            this.logger.log('Admin console index.html cached successfully');
        }
        catch (error) {
            this.logger.error('Failed to read admin console index.html on startup', { path: this.indexPath, message: error.message }, error.stack);
        }
    }
    async serveIndex(res) {
        this.config.ensureEnabled();
        if (!this.cachedIndexHtml) {
            this.logger.error('Cached index.html is not available');
            res.status(500).send('Internal Server Error');
            return;
        }
        try {
            let content = this.cachedIndexHtml;
            const basePath = this.config.getBasePath();
            const config = { basePath };
            const js = `window.__NEST_AUTH_CONFIG__ = ${JSON.stringify(config)};`;
            const configScriptTag = `<script>${js}</script>`;
            if (content.includes('<head>')) {
                content = content.replace('<head>', `${configScriptTag}<head>`);
            }
            res.setHeader('Content-Type', 'text/html');
            res.send(content);
        }
        catch (error) {
            this.logger.error('Failed to serve admin console index.html', { path: this.indexPath, message: error.message }, error.stack);
            res.status(500).send('Internal Server Error');
        }
    }
};
exports.AdminConsoleController = AdminConsoleController;
__decorate([
    (0, common_1.Get)(),
    __param(0, (0, common_1.Res)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], AdminConsoleController.prototype, "serveIndex", null);
exports.AdminConsoleController = AdminConsoleController = AdminConsoleController_1 = __decorate([
    (0, common_1.Controller)('auth/admin'),
    __metadata("design:paramtypes", [admin_console_config_service_1.AdminConsoleConfigService])
], AdminConsoleController);
//# sourceMappingURL=admin-console.controller.js.map