"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BootstrapAdminAuth = void 0;
const node_crypto_1 = __importDefault(require("node:crypto"));
const AppError_js_1 = require("../../shared/errors/AppError.js");
class BootstrapAdminAuth {
    authRepository;
    credentialStore;
    logger;
    options;
    constructor(authRepository, credentialStore, logger, options) {
        this.authRepository = authRepository;
        this.credentialStore = credentialStore;
        this.logger = logger;
        this.options = options;
    }
    async execute() {
        const existing = await this.credentialStore.load();
        if (existing?.jwt || existing?.credentials) {
            this.logger.info("Admin auth storage found for Quant Whisper bot.");
            return;
        }
        const credentials = this.createCredentials();
        this.logger.info("No signals admin auth storage found; attempting admin login bootstrap.");
        await this.authRepository.registerAdmin(credentials);
        const login = await this.authRepository.loginAdmin(credentials);
        await this.credentialStore.save({
            credentials,
            jwt: login.token,
            jwtExpiresAt: login.expiresAt
        });
        this.logger.info("Signals admin bootstrap completed and local session stored.");
    }
    createCredentials() {
        const password = this.options.adminPassword ?? node_crypto_1.default.randomBytes(32).toString("base64url");
        const username = this.options.adminUsername ?? this.options.adminEmail ?? `signals-admin-${node_crypto_1.default.randomBytes(5).toString("hex")}`;
        const email = this.options.adminEmail;
        if (!username || !password) {
            throw new AppError_js_1.ConfigurationError("Admin credentials could not be created.");
        }
        return {
            username,
            email,
            password,
            name: this.options.adminName
        };
    }
}
exports.BootstrapAdminAuth = BootstrapAdminAuth;
