"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); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdminAuthController = void 0;
const common_1 = require("@nestjs/common");
const admin_auth_service_1 = require("../services/admin-auth.service");
const admin_session_service_1 = require("../services/admin-session.service");
const admin_console_config_service_1 = require("../services/admin-console-config.service");
const login_dto_1 = require("../dto/login.dto");
const reset_password_dto_1 = require("../dto/reset-password.dto");
const signup_dto_1 = require("../dto/signup.dto");
const admin_session_guard_1 = require("../guards/admin-session.guard");
const current_admin_decorator_1 = require("../decorators/current-admin.decorator");
const admin_user_entity_1 = require("../entities/admin-user.entity");
const create_dashboard_admin_dto_1 = require("../dto/create-dashboard-admin.dto");
const admin_user_service_1 = require("../services/admin-user.service");
const security_util_1 = require("../../utils/security.util");
const user_service_1 = require("../../user/services/user.service");
const role_service_1 = require("../../role/services/role.service");
const tenant_service_1 = require("../../tenant/services/tenant.service");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const user_entity_1 = require("../../user/entities/user.entity");
const typeorm_3 = require("typeorm");
let AdminAuthController = class AdminAuthController {
    adminAuth;
    sessions;
    config;
    adminUsers;
    userService;
    roleService;
    tenantService;
    userRepository;
    constructor(adminAuth, sessions, config, adminUsers, userService, roleService, tenantService, userRepository) {
        this.adminAuth = adminAuth;
        this.sessions = sessions;
        this.config = config;
        this.adminUsers = adminUsers;
        this.userService = userService;
        this.roleService = roleService;
        this.tenantService = tenantService;
        this.userRepository = userRepository;
    }
    getCookieOptions() {
        const opts = this.config.getCookieOptions();
        const maxAge = this.sessions.getMaxAge();
        if (maxAge) {
            opts.maxAge = maxAge;
        }
        return opts;
    }
    async signup(dto) {
        this.config.ensureEnabled();
        const secretKey = this.config.getSecretKey();
        if (!secretKey) {
            throw new common_1.BadRequestException({
                message: 'Admin console secret key is not configured. Please configure adminConsole.secretKey in AuthModuleOptions.',
                code: 'ADMIN_CONSOLE_SECRET_NOT_CONFIGURED',
            });
        }
        if (!(0, security_util_1.compareKeys)(dto.secretKey, secretKey)) {
            throw new common_1.UnauthorizedException({
                message: 'Invalid secret key',
                code: 'INVALID_SECRET_KEY',
            });
        }
        const admin = await this.adminUsers.createAdmin({
            email: dto.email,
            password: dto.password,
            name: dto.name,
            metadata: dto.metadata || {},
        });
        return {
            message: 'Admin user created successfully',
            admin: this.toSafeAdmin(admin),
        };
    }
    async login(dto, res) {
        this.config.ensureEnabled();
        const admin = await this.adminAuth.validateCredentials(dto.email, dto.password);
        const token = this.sessions.createSession(admin);
        res.cookie(this.sessions.getCookieName(), token, this.getCookieOptions());
        return {
            message: 'Signed in successfully',
            admin: this.toSafeAdmin(admin),
        };
    }
    async logout(admin, res) {
        try {
            await this.sessions.invalidateSessionForAdmin(admin.id);
        }
        catch (error) {
            console.error('Failed to invalidate admin session:', error);
        }
        res.cookie(this.sessions.getCookieName(), '', {
            ...this.getCookieOptions(),
            maxAge: 0,
        });
        return { message: 'Signed out' };
    }
    async me(admin) {
        return this.toSafeAdmin(admin);
    }
    async publicConfig() {
        return {
            allowAdminManagement: this.config.allowAdminManagement(),
        };
    }
    async getDashboardStats() {
        const [totalUsers, activeUsers, verifiedUsers] = await Promise.all([
            this.userService.countUsers(),
            this.userService.countUsers({ where: { isActive: true } }),
            this.userService.countUsers({ where: { isVerified: true } }),
        ]);
        const roles = await this.roleService.getRoles();
        const tenants = await this.tenantService.getTenants({ order: { createdAt: 'DESC' } });
        const sevenDaysAgo = new Date();
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
        sevenDaysAgo.setHours(0, 0, 0, 0);
        const recentSignups = await this.userService.countUsers({
            where: { createdAt: (0, typeorm_3.MoreThanOrEqual)(sevenDaysAgo) },
        });
        const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        const activityData = [];
        for (let i = 6; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            date.setHours(0, 0, 0, 0);
            const dayName = dayNames[date.getDay()];
            activityData.push({ name: dayName, users: 0 });
        }
        const sevenDaysAgoStart = new Date();
        sevenDaysAgoStart.setDate(sevenDaysAgoStart.getDate() - 7);
        sevenDaysAgoStart.setHours(0, 0, 0, 0);
        const recentUsers = await this.userRepository.find({
            where: { createdAt: (0, typeorm_3.MoreThanOrEqual)(sevenDaysAgoStart) },
            select: ['createdAt'],
        });
        recentUsers.forEach((user) => {
            const signupDate = new Date(user.createdAt);
            signupDate.setHours(0, 0, 0, 0);
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            const daysDiff = Math.floor((today.getTime() - signupDate.getTime()) / (1000 * 60 * 60 * 24));
            if (daysDiff >= 0 && daysDiff <= 6) {
                const index = 6 - daysDiff;
                if (index >= 0 && index < activityData.length) {
                    activityData[index].users += 1;
                }
            }
        });
        return {
            stats: {
                totalUsers,
                activeUsers,
                verifiedUsers,
                totalRoles: roles.length,
                totalTenants: tenants.length,
                recentSignups,
            },
            activityData,
        };
    }
    async getSetupStatus() {
        this.config.ensureEnabled();
        const userCount = await this.userService.countUsers();
        const rolesCount = await this.roleService.getRoles();
        const needsSetup = userCount === 0 || rolesCount.length === 0;
        return {
            needsSetup,
            stats: {
                usersCount: userCount,
                rolesCount: rolesCount.length,
            },
            setupSteps: [
                {
                    id: 'roles',
                    title: 'Create Roles',
                    description: 'Set up roles and permissions for your users',
                    completed: rolesCount.length > 0,
                },
                {
                    id: 'users',
                    title: 'Create Users',
                    description: 'Add users to your system',
                    completed: userCount > 0,
                },
            ],
        };
    }
    async listAdmins() {
        if (!this.config.allowAdminManagement()) {
            throw new common_1.ForbiddenException('Admin management disabled');
        }
        const admins = await this.adminUsers.listAdmins();
        return {
            data: admins.map((admin) => this.toSafeAdmin(admin)),
        };
    }
    async createAdmin(dto) {
        if (!this.config.allowAdminManagement()) {
            throw new common_1.ForbiddenException('Admin management disabled');
        }
        const admin = await this.adminUsers.createAdmin(dto);
        return { admin: this.toSafeAdmin(admin) };
    }
    async updateAdmin(id, dto) {
        if (!this.config.allowAdminManagement()) {
            throw new common_1.ForbiddenException('Admin management disabled');
        }
        const admin = await this.adminUsers.updateAdmin(id, dto);
        return { admin: this.toSafeAdmin(admin) };
    }
    async deleteAdmin(id) {
        if (!this.config.allowAdminManagement()) {
            throw new common_1.ForbiddenException('Admin management disabled');
        }
        await this.adminUsers.deleteAdmin(id);
        return { message: 'Admin deleted successfully' };
    }
    async resetPassword(dto) {
        this.config.ensureEnabled();
        const secretKey = this.config.getSecretKey();
        if (!secretKey) {
            throw new common_1.UnauthorizedException({
                message: 'Admin console secret key not configured',
                code: 'SECRET_KEY_NOT_CONFIGURED',
            });
        }
        if (!(0, security_util_1.compareKeys)(dto.secretKey, secretKey)) {
            throw new common_1.UnauthorizedException({
                message: 'Invalid secret key',
                code: 'INVALID_SECRET_KEY',
            });
        }
        const admin = await this.adminUsers.findByEmail(dto.email);
        if (!admin) {
            throw new common_1.UnauthorizedException({
                message: 'Invalid credentials',
                code: 'INVALID_CREDENTIALS',
            });
        }
        await this.adminUsers.updateAdmin(admin.id, { password: dto.newPassword });
        return {
            message: 'Password reset successfully',
        };
    }
    toSafeAdmin(admin) {
        return {
            id: admin.id,
            email: admin.email,
            name: admin.name,
            metadata: admin.metadata ?? {},
            lastLoginAt: admin.lastLoginAt,
            createdAt: admin.createdAt,
            updatedAt: admin.updatedAt,
        };
    }
};
exports.AdminAuthController = AdminAuthController;
__decorate([
    (0, common_1.Post)('signup'),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [signup_dto_1.AdminSignupDto]),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "signup", null);
__decorate([
    (0, common_1.Post)('login'),
    __param(0, (0, common_1.Body)()),
    __param(1, (0, common_1.Res)({ passthrough: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [login_dto_1.AdminLoginDto, Object]),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "login", null);
__decorate([
    (0, common_1.Post)('logout'),
    (0, common_1.UseGuards)(admin_session_guard_1.AdminSessionGuard),
    __param(0, (0, current_admin_decorator_1.CurrentAdmin)()),
    __param(1, (0, common_1.Res)({ passthrough: true })),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [admin_user_entity_1.NestAuthAdminUser, Object]),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "logout", null);
__decorate([
    (0, common_1.Get)('me'),
    (0, common_1.UseGuards)(admin_session_guard_1.AdminSessionGuard),
    __param(0, (0, current_admin_decorator_1.CurrentAdmin)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [admin_user_entity_1.NestAuthAdminUser]),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "me", null);
__decorate([
    (0, common_1.Get)('config'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "publicConfig", null);
__decorate([
    (0, common_1.Get)('api/stats'),
    (0, common_1.UseGuards)(admin_session_guard_1.AdminSessionGuard),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "getDashboardStats", null);
__decorate([
    (0, common_1.Get)('setup-status'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "getSetupStatus", null);
__decorate([
    (0, common_1.Get)('admins'),
    (0, common_1.UseGuards)(admin_session_guard_1.AdminSessionGuard),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "listAdmins", null);
__decorate([
    (0, common_1.Post)('admins'),
    (0, common_1.UseGuards)(admin_session_guard_1.AdminSessionGuard),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [create_dashboard_admin_dto_1.CreateDashboardAdminDto]),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "createAdmin", null);
__decorate([
    (0, common_1.Patch)('admins/:id'),
    (0, common_1.UseGuards)(admin_session_guard_1.AdminSessionGuard),
    __param(0, (0, common_1.Param)('id')),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, create_dashboard_admin_dto_1.UpdateDashboardAdminDto]),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "updateAdmin", null);
__decorate([
    (0, common_1.Delete)('admins/:id'),
    (0, common_1.UseGuards)(admin_session_guard_1.AdminSessionGuard),
    __param(0, (0, common_1.Param)('id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "deleteAdmin", null);
__decorate([
    (0, common_1.Post)('reset-password'),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [reset_password_dto_1.AdminResetPasswordDto]),
    __metadata("design:returntype", Promise)
], AdminAuthController.prototype, "resetPassword", null);
exports.AdminAuthController = AdminAuthController = __decorate([
    (0, common_1.Controller)('auth/admin'),
    __param(7, (0, typeorm_1.InjectRepository)(user_entity_1.NestAuthUser)),
    __metadata("design:paramtypes", [admin_auth_service_1.AdminAuthService,
        admin_session_service_1.AdminSessionService,
        admin_console_config_service_1.AdminConsoleConfigService,
        admin_user_service_1.AdminUserService,
        user_service_1.UserService,
        role_service_1.RoleService,
        tenant_service_1.TenantService,
        typeorm_2.Repository])
], AdminAuthController);
//# sourceMappingURL=admin-auth.controller.js.map