"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);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var TeachersService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TeachersService = void 0;
const common_1 = require("@nestjs/common");
const mongoose_1 = require("@nestjs/mongoose");
const mongoose_2 = require("mongoose");
const teacher_schema_1 = require("./schemas/teacher.schema");
const bcrypt = __importStar(require("bcryptjs"));
const BCRYPT_ROUNDS = Number(process.env.BCRYPT_ROUNDS || 10);
let TeachersService = TeachersService_1 = class TeachersService {
    teacherModel;
    logger = new common_1.Logger(TeachersService_1.name);
    constructor(teacherModel) {
        this.teacherModel = teacherModel;
    }
    async onModuleInit() {
        await this.teacherModel.updateMany({ email: '' }, { $unset: { email: 1 } });
        await this.teacherModel.syncIndexes();
    }
    normEmail(email) {
        return (email || '').trim().toLowerCase();
    }
    normStr(v) {
        return (v || '').trim();
    }
    async handleDupKey(err) {
        if (err?.code === 11000) {
            const fields = Object.keys(err.keyPattern || {});
            if (fields.includes('email'))
                throw new common_1.BadRequestException('Email already exists');
            if (fields.includes('uniqueId'))
                throw new common_1.BadRequestException('Duplicate teacher ID generated. Please try again.');
            throw new common_1.BadRequestException('A duplicate value was detected. Please check your input.');
        }
        throw err;
    }
    async create(dto) {
        const email = dto.email ? this.normEmail(dto.email) : undefined;
        if (email) {
            const exists = await this.teacherModel.findOne({ email }).lean();
            if (exists)
                throw new common_1.BadRequestException('Email already exists');
        }
        const hashedPassword = dto.password
            ? await bcrypt.hash(dto.password, BCRYPT_ROUNDS)
            : undefined;
        const { generateTeacherId } = await Promise.resolve().then(() => __importStar(require('../common/utils/id-generator')));
        const data = {
            name: this.normStr(dto.name),
            ...(email ? { email } : {}),
            ...(hashedPassword ? { password: hashedPassword } : {}),
            role: 'teacher',
            isActive: dto.isActive !== undefined ? dto.isActive : true,
            designation: dto.designation || undefined,
            subject: dto.subject ? this.normStr(dto.subject) : undefined,
            phone: dto.phone ? this.normStr(dto.phone) : undefined,
            dateOfBirth: dto.dateOfBirth,
            joinDate: dto.joinDate,
            mobileNumber: this.normStr(dto.mobileNumber),
            fatherName: dto.fatherName ? this.normStr(dto.fatherName) : undefined,
            motherName: dto.motherName ? this.normStr(dto.motherName) : undefined,
            adhaarNumber: dto.adhaarNumber ? this.normStr(dto.adhaarNumber) : undefined,
            panNumber: dto.panNumber ? this.normStr(dto.panNumber) : undefined,
            address: this.normStr(dto.address),
            highestQualification: this.normStr(dto.highestQualification),
            photoUrl: dto.photoUrl ? this.normStr(dto.photoUrl) : undefined,
            signature: dto.signature ? this.normStr(dto.signature) : undefined,
            customDocuments: dto.customDocuments || [],
            customImages: dto.customImages || [],
            education: dto.education || [],
            bankName: dto.bankName ? this.normStr(dto.bankName) : undefined,
            accountNumber: dto.accountNumber ? this.normStr(dto.accountNumber) : undefined,
            accountType: dto.accountType ? this.normStr(dto.accountType) : undefined,
            ifscNumber: dto.ifscNumber ? this.normStr(dto.ifscNumber) : undefined,
            pfMemberId: dto.pfMemberId ? this.normStr(dto.pfMemberId) : undefined,
            pfAccountNumber: dto.pfAccountNumber ? this.normStr(dto.pfAccountNumber) : undefined,
            employeeName: dto.employeeName ? this.normStr(dto.employeeName) : undefined,
            kycStatus: dto.kycStatus ? this.normStr(dto.kycStatus) : undefined,
            schoolLeavingDate: dto.schoolLeavingDate || undefined,
            leavingReason: dto.leavingReason ? this.normStr(dto.leavingReason) : undefined,
        };
        for (let attempt = 0; attempt < 3; attempt++) {
            const uniqueId = await generateTeacherId(this.teacherModel);
            try {
                const doc = await this.teacherModel.create({ ...data, uniqueId });
                return doc.toJSON();
            }
            catch (err) {
                if (err?.code === 11000 && Object.keys(err.keyPattern || {}).includes('uniqueId')) {
                    continue;
                }
                await this.handleDupKey(err);
            }
        }
        throw new common_1.BadRequestException('Could not generate unique teacher ID. Please try again.');
    }
    async backfillTeacherIds() {
        const { generateTeacherId } = await Promise.resolve().then(() => __importStar(require('../common/utils/id-generator')));
        const noIdFilter = { $or: [{ uniqueId: { $exists: false } }, { uniqueId: null }, { uniqueId: '' }] };
        const teachers = await this.teacherModel.find(noIdFilter, { _id: 1 }).lean();
        let updated = 0;
        let failed = 0;
        for (const t of teachers) {
            try {
                for (let attempt = 0; attempt < 3; attempt++) {
                    const uniqueId = await generateTeacherId(this.teacherModel);
                    try {
                        const result = await this.teacherModel.updateOne({ _id: t._id, ...noIdFilter }, { $set: { uniqueId } });
                        if (result.modifiedCount > 0)
                            updated++;
                        break;
                    }
                    catch (err) {
                        if (err?.code === 11000 && attempt < 2)
                            continue;
                        throw err;
                    }
                }
            }
            catch (err) {
                this.logger.warn(`Failed to backfill uniqueId for teacher ${t._id}`, err);
                failed++;
            }
        }
        return { total: teachers.length, updated, failed };
    }
    async findByEmail(email) {
        return this.teacherModel.findOne({ email: this.normEmail(email) }).lean();
    }
    async findByIdForAuth(id) {
        return this.teacherModel.findById(id).lean();
    }
    async findByPhone(phone) {
        return this.teacherModel.findOne({ phone: this.normStr(phone) }).lean();
    }
    findAll(isActive) {
        const filter = {};
        if (isActive !== undefined)
            filter.isActive = isActive;
        return this.teacherModel
            .find(filter, { password: 0 })
            .sort({ createdAt: -1 })
            .limit(5000)
            .lean({ virtuals: true });
    }
    async searchTeachers(query, limit = 50) {
        if (!query || query.trim().length === 0) {
            return [];
        }
        const escaped = query.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        const searchRegex = new RegExp(escaped, 'i');
        return this.teacherModel
            .find({
            $or: [
                { name: searchRegex },
                { email: searchRegex },
                { subject: searchRegex },
                { uniqueId: searchRegex },
            ],
        }, { password: 0 })
            .limit(Math.min(limit, 100))
            .sort({ name: 1 })
            .lean({ virtuals: true });
    }
    async findMinimal() {
        return this.teacherModel
            .find({ isActive: true }, { name: 1, subject: 1 })
            .sort({ name: 1 })
            .limit(1000)
            .lean({ virtuals: true });
    }
    findOne(id) {
        return this.teacherModel.findById(id, { password: 0 }).lean({ virtuals: true });
    }
    async update(id, dto) {
        const $set = {};
        const $unset = {};
        const setOrUnset = (field, val, normalize = true) => {
            const v = val && normalize ? this.normStr(val) : val;
            if (v)
                $set[field] = v;
            else
                $unset[field] = 1;
        };
        if (dto.isActive !== undefined)
            $set.isActive = dto.isActive;
        if (dto.email !== undefined) {
            const e = dto.email ? this.normEmail(dto.email) : '';
            if (e)
                $set.email = e;
            else
                $unset.email = 1;
        }
        if (dto.name !== undefined)
            $set.name = this.normStr(dto.name);
        if (dto.designation !== undefined)
            setOrUnset('designation', dto.designation);
        if (dto.subject !== undefined)
            setOrUnset('subject', dto.subject);
        if (dto.phone !== undefined)
            setOrUnset('phone', dto.phone);
        if (dto.dateOfBirth !== undefined) {
            if (dto.dateOfBirth)
                $set.dateOfBirth = dto.dateOfBirth;
            else
                $unset.dateOfBirth = 1;
        }
        if (dto.joinDate !== undefined) {
            if (dto.joinDate)
                $set.joinDate = dto.joinDate;
            else
                $unset.joinDate = 1;
        }
        if (dto.fatherName !== undefined)
            setOrUnset('fatherName', dto.fatherName);
        if (dto.motherName !== undefined)
            setOrUnset('motherName', dto.motherName);
        if (dto.mobileNumber !== undefined)
            setOrUnset('mobileNumber', dto.mobileNumber);
        if (dto.adhaarNumber !== undefined)
            setOrUnset('adhaarNumber', dto.adhaarNumber);
        if (dto.panNumber !== undefined)
            setOrUnset('panNumber', dto.panNumber);
        if (dto.address !== undefined)
            setOrUnset('address', dto.address);
        if (dto.highestQualification !== undefined)
            setOrUnset('highestQualification', dto.highestQualification);
        if (dto.photoUrl !== undefined)
            setOrUnset('photoUrl', dto.photoUrl);
        if (dto.signature !== undefined)
            setOrUnset('signature', dto.signature);
        if (dto.customDocuments !== undefined)
            $set.customDocuments = dto.customDocuments;
        if (dto.customImages !== undefined)
            $set.customImages = dto.customImages;
        if (dto.education !== undefined)
            $set.education = dto.education;
        if (dto.bankName !== undefined)
            setOrUnset('bankName', dto.bankName);
        if (dto.accountNumber !== undefined)
            setOrUnset('accountNumber', dto.accountNumber);
        if (dto.accountType !== undefined)
            setOrUnset('accountType', dto.accountType);
        if (dto.ifscNumber !== undefined)
            setOrUnset('ifscNumber', dto.ifscNumber);
        if (dto.pfMemberId !== undefined)
            setOrUnset('pfMemberId', dto.pfMemberId);
        if (dto.pfAccountNumber !== undefined)
            setOrUnset('pfAccountNumber', dto.pfAccountNumber);
        if (dto.employeeName !== undefined)
            setOrUnset('employeeName', dto.employeeName);
        if (dto.kycStatus !== undefined)
            setOrUnset('kycStatus', dto.kycStatus);
        if (dto.schoolLeavingDate !== undefined) {
            if (dto.schoolLeavingDate)
                $set.schoolLeavingDate = dto.schoolLeavingDate;
            else
                $unset.schoolLeavingDate = 1;
        }
        if (dto.leavingReason !== undefined)
            setOrUnset('leavingReason', dto.leavingReason);
        if (dto.password !== undefined && dto.password.trim().length > 0) {
            $set.password = await bcrypt.hash(dto.password, BCRYPT_ROUNDS);
        }
        const updateOps = {};
        if (Object.keys($set).length)
            updateOps.$set = $set;
        if (Object.keys($unset).length)
            updateOps.$unset = $unset;
        try {
            const updated = await this.teacherModel.findByIdAndUpdate(id, updateOps, {
                new: true,
                projection: { password: 0 },
            });
            if (!updated)
                throw new common_1.NotFoundException('Teacher not found');
            return updated.toJSON();
        }
        catch (err) {
            if (err instanceof common_1.NotFoundException)
                throw err;
            await this.handleDupKey(err);
        }
    }
    async toggleActive(id) {
        const teacher = await this.teacherModel.findById(id, { isActive: 1 }).lean();
        if (!teacher)
            throw new common_1.NotFoundException('Teacher not found');
        const newState = !teacher.isActive;
        await this.teacherModel.updateOne({ _id: id }, { $set: { isActive: newState } });
        return { _id: id, isActive: newState };
    }
    async delete(id) {
        const deleted = await this.teacherModel.findByIdAndDelete(id);
        if (!deleted)
            throw new common_1.NotFoundException('Teacher not found');
        return { message: 'Teacher deleted successfully' };
    }
    async updatePassword(id, newPasswordHash) {
        const updated = await this.teacherModel.findByIdAndUpdate(id, { password: newPasswordHash }, { new: true });
        if (!updated)
            throw new common_1.NotFoundException('Teacher not found');
        return { message: 'Password updated successfully' };
    }
    async updateSelfProfile(id, data) {
        const update = {};
        if (data.name !== undefined) {
            const trimmed = (data.name || '').trim();
            if (!trimmed)
                throw new common_1.BadRequestException('Name cannot be empty');
            update.name = trimmed;
        }
        if (data.phone !== undefined)
            update.phone = data.phone ? data.phone.trim() : undefined;
        if (data.photoUrl !== undefined)
            update.photoUrl = data.photoUrl ? data.photoUrl.trim() : undefined;
        const updated = await this.teacherModel.findByIdAndUpdate(id, update, { new: true, projection: { password: 0 } }).lean({ virtuals: true });
        if (!updated)
            throw new common_1.NotFoundException('Teacher not found');
        return updated;
    }
    async updateEmail(id, newEmail) {
        const email = this.normEmail(newEmail);
        if (!email)
            throw new common_1.BadRequestException('Email is required');
        const exists = await this.teacherModel.findOne({ email, _id: { $ne: id } }).lean();
        if (exists)
            throw new common_1.BadRequestException('Email already in use');
        const updated = await this.teacherModel.findByIdAndUpdate(id, { email }, { new: true, projection: { password: 0 } }).lean({ virtuals: true });
        if (!updated)
            throw new common_1.NotFoundException('Teacher not found');
        return updated;
    }
    async updateNotificationPrefs(id, prefs) {
        const update = {};
        if (prefs.email !== undefined)
            update['notificationPrefs.email'] = prefs.email;
        if (prefs.whatsapp !== undefined)
            update['notificationPrefs.whatsapp'] = prefs.whatsapp;
        const updated = await this.teacherModel.findByIdAndUpdate(id, { $set: update }, { new: true, projection: { password: 0 } }).lean({ virtuals: true });
        if (!updated)
            throw new common_1.NotFoundException('Teacher not found');
        return updated;
    }
};
exports.TeachersService = TeachersService;
exports.TeachersService = TeachersService = TeachersService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, mongoose_1.InjectModel)(teacher_schema_1.Teacher.name)),
    __metadata("design:paramtypes", [mongoose_2.Model])
], TeachersService);
//# sourceMappingURL=teachers.service.js.map