"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);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdminAuthService = void 0;
const common_1 = require("@nestjs/common");
const admin_user_service_1 = require("./admin-user.service");
const admin_session_service_1 = require("./admin-session.service");
const admin_console_config_service_1 = require("./admin-console-config.service");
const debug_logger_service_1 = require("../../core/services/debug-logger.service");
const security_util_1 = require("../../utils/security.util");
let AdminAuthService = class AdminAuthService {
    adminUsers;
    sessions;
    config;
    debugLogger;
    constructor(adminUsers, sessions, config, debugLogger) {
        this.adminUsers = adminUsers;
        this.sessions = sessions;
        this.config = config;
        this.debugLogger = debugLogger;
    }
    async validateCredentials(email, password) {
        const admin = await this.adminUsers.findByEmail(email);
        if (!admin) {
            throw new common_1.UnauthorizedException('Invalid credentials');
        }
        const valid = await admin.validatePassword(password);
        if (!valid) {
            throw new common_1.UnauthorizedException('Invalid credentials');
        }
        admin.lastLoginAt = new Date();
        await admin.save();
        return admin;
    }
    async createInitialAdmin(payload) {
        this.config.ensureEnabled();
        const configuredKey = this.config.getSecretKey();
        if (!configuredKey) {
            throw new common_1.BadRequestException({
                message: 'Admin console setup key is not configured.',
                code: 'ADMIN_CONSOLE_SETUP_DISABLED',
            });
        }
        if (!(0, security_util_1.compareKeys)(payload.setupKey, configuredKey)) {
            throw new common_1.UnauthorizedException({
                message: 'Invalid admin console setup key.',
                code: 'INVALID_ADMIN_CONSOLE_SETUP_KEY',
            });
        }
        const existingAdmins = await this.adminUsers.listAdmins();
        if (existingAdmins.length > 0) {
            throw new common_1.BadRequestException({
                message: 'Admin users already exist. Use the dashboard to manage administrators.',
                code: 'ADMIN_USERS_ALREADY_INITIALIZED',
            });
        }
        const maskedEmail = payload.email.replace(/(.{2})(.*)(@.*)/, '$1****$3');
        this.debugLogger.info('Creating initial admin console user', 'AdminAuthService', {
            email: maskedEmail,
        });
        return this.adminUsers.createAdmin({
            email: payload.email,
            password: payload.password,
            name: payload.name,
            metadata: payload.metadata,
        });
    }
    createSession(admin) {
        return this.sessions.createSession(admin);
    }
};
exports.AdminAuthService = AdminAuthService;
exports.AdminAuthService = AdminAuthService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [admin_user_service_1.AdminUserService,
        admin_session_service_1.AdminSessionService,
        admin_console_config_service_1.AdminConsoleConfigService,
        debug_logger_service_1.DebugLoggerService])
], AdminAuthService);
//# sourceMappingURL=admin-auth.service.js.map