"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
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 __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
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.AuthService = void 0;
const common_1 = require("@nestjs/common");
const jwt_1 = require("@nestjs/jwt");
const bcrypt = __importStar(require("bcryptjs"));
const admin_service_1 = require("../admin/admin.service");
const students_service_1 = require("../students/students.service");
const teachers_service_1 = require("../teachers/teachers.service");
const role_enum_1 = require("../common/roles/role.enum");
const otp_service_1 = require("./otp.service");
const notification_service_1 = require("./notification.service");
const AUTH_DEBUG = (process.env.AUTH_DEBUG_OTP || '').toLowerCase() === 'true';
const BCRYPT_ROUNDS = Number(process.env.BCRYPT_ROUNDS || 10);
let AuthService = class AuthService {
    jwtService;
    adminService;
    teachersService;
    studentsService;
    otpService;
    notificationService;
    constructor(jwtService, adminService, teachersService, studentsService, otpService, notificationService) {
        this.jwtService = jwtService;
        this.adminService = adminService;
        this.teachersService = teachersService;
        this.studentsService = studentsService;
        this.otpService = otpService;
        this.notificationService = notificationService;
    }
    normalizeEmail(value) {
        return (value || '').trim().toLowerCase();
    }
    normalizePhone(value) {
        return (value || '').replace(/[^\d+]/g, '');
    }
    getJwtExpiresIn() {
        return process.env.JWT_EXPIRES_IN || '1d';
    }
    async findUserByChannel(channel, identifierRaw) {
        if (channel === 'email') {
            const email = this.normalizeEmail(identifierRaw);
            const [admin, teacher, student] = await Promise.all([
                this.adminService.findByEmail?.(email),
                this.teachersService.findByEmail?.(email),
                this.studentsService.findByEmail?.(email),
            ]);
            if (admin)
                return { user: admin, role: role_enum_1.Role.ADMIN };
            if (teacher)
                return { user: teacher, role: role_enum_1.Role.TEACHER };
            if (student)
                return { user: student, role: role_enum_1.Role.STUDENT };
            return null;
        }
        else {
            const phone = this.normalizePhone(identifierRaw);
            const [admin, teacher, student] = await Promise.all([
                this.adminService.findByPhone?.(phone),
                this.teachersService.findByPhone?.(phone),
                this.studentsService.findByPhone?.(phone),
            ]);
            if (admin)
                return { user: admin, role: role_enum_1.Role.ADMIN };
            if (teacher)
                return { user: teacher, role: role_enum_1.Role.TEACHER };
            if (student)
                return { user: student, role: role_enum_1.Role.STUDENT };
            return null;
        }
    }
    resolveContact(channel, value, user) {
        if (channel === 'email') {
            const email = this.normalizeEmail(value || user?.email || '');
            if (!email)
                throw new common_1.BadRequestException('Invalid or expired OTP. Please try again.');
            return email;
        }
        const phone = (this.normalizePhone(value || '') || (user?.phone ?? '')).trim();
        if (!phone)
            throw new common_1.BadRequestException('Invalid or expired OTP. Please try again.');
        return phone;
    }
    async validateUser(email, password) {
        const normalizedEmail = (email || '').trim().toLowerCase();
        const admin = await this.adminService.findByEmail?.(normalizedEmail);
        if (admin && admin.password && (await bcrypt.compare(password, admin.password))) {
            return { id: admin._id, email: admin.email, role: role_enum_1.Role.ADMIN };
        }
        const teacher = await this.teachersService.findByEmail?.(normalizedEmail);
        if (teacher && teacher.password && (await bcrypt.compare(password, teacher.password))) {
            return { id: teacher._id, email: teacher.email, role: role_enum_1.Role.TEACHER };
        }
        const student = await this.studentsService.findByEmailForAuth?.(normalizedEmail);
        if (student && student.password && (await bcrypt.compare(password, student.password))) {
            return { id: student._id, email: student.email, role: role_enum_1.Role.STUDENT };
        }
        throw new common_1.UnauthorizedException('Invalid credentials');
    }
    async login(email, password) {
        const user = await this.validateUser(email, password);
        const payload = { sub: user.id, email: user.email, role: user.role };
        const expiresIn = this.getJwtExpiresIn();
        return {
            access_token: this.jwtService.sign(payload, { expiresIn }),
            user: { id: user.id, email: user.email, role: user.role },
            expires_in: expiresIn,
        };
    }
    async getMe(user) {
        const { id, role } = user;
        let email = user.email;
        let name = email?.split('@')[0] || 'User';
        let photoUrl;
        try {
            if (role === role_enum_1.Role.ADMIN) {
                const admin = await this.adminService.findById(id);
                email = admin?.email || email;
                name = admin?.name || admin?.email?.split('@')[0] || 'Admin';
                photoUrl = admin?.photoUrl;
            }
            else if (role === role_enum_1.Role.TEACHER) {
                const teacher = await this.teachersService.findOne(id);
                email = teacher?.email || email;
                name = teacher?.name || teacher?.email?.split('@')[0] || 'Teacher';
                photoUrl = teacher?.photoUrl;
            }
            else if (role === role_enum_1.Role.STUDENT) {
                const student = await this.studentsService.findByIdForAuth(id);
                email = student?.email || email;
                name = student?.name || student?.email?.split('@')[0] || 'Student';
                photoUrl = student?.profileImageUrl || student?.documents?.photoUrl;
            }
        }
        catch (error) {
            console.error('Error fetching user details for getMe:', error);
        }
        return { id, email, role, name, photoUrl };
    }
    async sendOtp(channel, value) {
        const found = await this.findUserByChannel(channel, value);
        if (found) {
            const to = this.resolveContact(channel, value, found.user);
            const leftMs = await this.otpService.getResendLeftMs(channel, to);
            if (leftMs > 0) {
                const left = Math.ceil(leftMs / 1000);
                throw new common_1.BadRequestException(`Please wait ${left}s before requesting another OTP.`);
            }
            const code = await this.otpService.create(channel, to);
            const expiresInMinutes = this.otpService.getExpiryMinutes();
            if (AUTH_DEBUG) {
                const keyId = this.otpService.debugNormalizedValue(channel, to);
                console.log(`[AUTH_DEBUG] OTP created for ${channel}:${keyId} code=${code}`);
            }
            await this.notificationService.sendOtp(channel, to, code, expiresInMinutes);
        }
        return { message: 'If the account exists, an OTP has been sent.' };
    }
    async verifyOtp(channel, to, otp) {
        const found = await this.findUserByChannel(channel, to);
        if (!found)
            throw new common_1.BadRequestException('Invalid or expired OTP. Please try again.');
        const contact = this.resolveContact(channel, to, found.user);
        if (AUTH_DEBUG) {
            const keyId = this.otpService.debugNormalizedValue(channel, contact);
            console.log(`[AUTH_DEBUG] Checking ${channel}:${keyId} with otp=${otp}`);
        }
        await this.otpService.check(channel, contact, otp);
        const { attemptsUsed, lockedUntil } = await this.otpService.getAttemptsInfo(channel, contact);
        return { ok: true, attemptsUsed, lockedUntil };
    }
    async resendOtp(channel, to) {
        const found = await this.findUserByChannel(channel, to);
        if (!found)
            return { message: 'If the account exists, a new OTP has been sent.' };
        const contact = this.resolveContact(channel, to, found.user);
        const leftMs = await this.otpService.getResendLeftMs(channel, contact);
        if (leftMs > 0) {
            const left = Math.ceil(leftMs / 1000);
            throw new common_1.BadRequestException(`Please wait ${left}s before requesting another OTP.`);
        }
        const code = await this.otpService.create(channel, contact);
        await this.otpService.markResent(channel, contact);
        if (AUTH_DEBUG) {
            const keyId = this.otpService.debugNormalizedValue(channel, contact);
            console.log(`[AUTH_DEBUG] OTP resent for ${channel}:${keyId} code=${code}`);
        }
        const expiresInMinutes = this.otpService.getExpiryMinutes();
        await this.notificationService.sendOtp(channel, contact, code, expiresInMinutes);
        return { message: 'OTP resent successfully.' };
    }
    async updatePasswordForUser(userId, role, newPasswordHashed) {
        if (role === role_enum_1.Role.ADMIN)
            return this.adminService.updatePassword(userId, newPasswordHashed);
        if (role === role_enum_1.Role.TEACHER)
            return this.teachersService.updatePassword(userId, newPasswordHashed);
        if (role === role_enum_1.Role.STUDENT)
            return this.studentsService.updatePassword(userId, newPasswordHashed);
        throw new common_1.BadRequestException('Unsupported role for password update.');
    }
    async resetPassword(dto) {
        const { channel, value, otp, newPassword } = dto;
        const found = await this.findUserByChannel(channel, value);
        if (!found)
            throw new common_1.BadRequestException('Invalid or expired OTP. Please try again.');
        const contact = this.resolveContact(channel, value, found.user);
        if (AUTH_DEBUG) {
            const keyId = this.otpService.debugNormalizedValue(channel, contact);
            console.log(`[AUTH_DEBUG] Reset password verify ${channel}:${keyId} otp=${otp}`);
        }
        await this.otpService.verify(channel, contact, otp);
        const hashed = await bcrypt.hash(newPassword, BCRYPT_ROUNDS);
        await this.updatePasswordForUser(found.user._id, found.role, hashed);
        return { message: 'Password reset successful.' };
    }
};
exports.AuthService = AuthService;
exports.AuthService = AuthService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [jwt_1.JwtService,
        admin_service_1.AdminService,
        teachers_service_1.TeachersService,
        students_service_1.StudentsService,
        otp_service_1.OtpService,
        notification_service_1.NotificationService])
], AuthService);
//# sourceMappingURL=auth.service.js.map