"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 swagger_1 = require("@nestjs/swagger");
const path_1 = require("path");
const fs_1 = require("fs");
const admin_console_config_service_1 = require("../services/admin-console-config.service");
const public_decorator_1 = require("../../core/decorators/public.decorator");
const candidateStaticRoots = [
    (0, path_1.join)(__dirname, '..', 'static'),
    (0, path_1.join)(process.cwd(), 'node_modules', '@ackplus', 'nest-auth', 'dist', 'lib', 'admin-console', 'static'),
    (0, path_1.join)(process.cwd(), 'packages', 'nest-auth', 'dist', 'lib', 'admin-console', 'static'),
    (0, path_1.join)(process.cwd(), '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 null;
}
let AdminConsoleController = AdminConsoleController_1 = class AdminConsoleController {
    config;
    logger = new common_1.Logger(AdminConsoleController_1.name);
    cachedIndexHtml = null;
    staticRoot = resolveStaticRoot();
    indexPath = this.staticRoot ? (0, path_1.join)(this.staticRoot, 'index.html') : null;
    constructor(config) {
        this.config = config;
    }
    onModuleInit() {
        if (this.config.getConfig().enabled === false) {
            return;
        }
        if (!this.indexPath) {
            this.logger.warn('Admin console UI bundle not found (no static/index.html). The admin API still works; ' +
                'run `pnpm -F @ackplus/nest-auth-admin build` to serve the dashboard at /auth/admin.');
            return;
        }
        try {
            this.cachedIndexHtml = (0, fs_1.readFileSync)(this.indexPath, 'utf8');
            this.logger.log('Admin console UI bundle loaded');
        }
        catch (error) {
            this.logger.warn(`Admin console UI bundle could not be read at ${this.indexPath}: ${error.message}`);
        }
    }
    async serveIndex(res) {
        this.config.ensureEnabled();
        if (!this.cachedIndexHtml) {
            res
                .status(404)
                .type('text/plain')
                .send('Admin console UI is not bundled in this build. The admin API is available under ' +
                '/auth/admin/api/*. To serve the dashboard UI, build @ackplus/nest-auth-admin.');
            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, swagger_1.ApiExcludeController)(),
    (0, public_decorator_1.Public)(),
    (0, common_1.Controller)(),
    __metadata("design:paramtypes", [admin_console_config_service_1.AdminConsoleConfigService])
], AdminConsoleController);
//# sourceMappingURL=admin-console.controller.js.map