"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.ClassesService = void 0;
const common_1 = require("@nestjs/common");
const mongoose_1 = require("@nestjs/mongoose");
const class_schema_1 = require("./schemas/class.schema");
const section_schema_1 = require("../sections/schemas/section.schema");
const student_schema_1 = require("../students/schemas/student.schema");
const mongoose_2 = require("mongoose");
const mongo_serializer_1 = require("../common/utils/mongo-serializer");
let ClassesService = class ClassesService {
    classModel;
    sectionModel;
    studentModel;
    constructor(classModel, sectionModel, studentModel) {
        this.classModel = classModel;
        this.sectionModel = sectionModel;
        this.studentModel = studentModel;
    }
    lc(v) {
        return (v || '').trim().toLowerCase();
    }
    handleDup(err) {
        if (err?.code === 11000) {
            const fields = Object.keys(err?.keyPattern || {});
            if (fields.includes('name')) {
                throw new common_1.BadRequestException('Class already exists');
            }
            if (fields.includes('order')) {
                throw new common_1.BadRequestException('Class order must be unique');
            }
            throw new common_1.BadRequestException('Duplicate value');
        }
        throw err;
    }
    async create(dto) {
        const name = this.lc(dto.name);
        const exists = await this.classModel.findOne({ name }).lean();
        if (exists)
            throw new common_1.BadRequestException('Class already exists');
        try {
            const doc = await this.classModel.create({ name, order: dto.order });
            return doc.toJSON();
        }
        catch (err) {
            this.handleDup(err);
        }
    }
    async findAll() {
        const classes = await this.classModel
            .find()
            .sort({ order: 1, name: 1 })
            .lean();
        return (0, mongo_serializer_1.toJSON)(classes);
    }
    async findOne(id) {
        const classDoc = await this.classModel.findById(id).lean();
        return (0, mongo_serializer_1.toJSON)(classDoc);
    }
    async update(id, dto) {
        const update = {};
        if (dto.name !== undefined) {
            const newName = this.lc(dto.name);
            const existing = await this.classModel.findOne({
                name: newName,
                _id: { $ne: id }
            }).lean();
            if (existing) {
                throw new common_1.BadRequestException('Class name already exists');
            }
            update.name = newName;
        }
        if (dto.order !== undefined) {
            const existingOrder = await this.classModel.findOne({
                order: dto.order,
                _id: { $ne: id }
            }).lean();
            if (existingOrder) {
                throw new common_1.BadRequestException('Class order already exists. Please choose a different order.');
            }
            update.order = dto.order;
        }
        try {
            const classDoc = await this.classModel
                .findByIdAndUpdate(id, update, { new: true, runValidators: true })
                .lean();
            return (0, mongo_serializer_1.toJSON)(classDoc);
        }
        catch (err) {
            this.handleDup(err);
        }
    }
    async delete(id) {
        const sectionCount = await this.sectionModel.countDocuments({ classId: id });
        if (sectionCount > 0) {
            throw new common_1.BadRequestException(`Cannot delete class: ${sectionCount} section(s) are assigned to this class. Please reassign or delete them first.`);
        }
        const studentCount = await this.studentModel.countDocuments({ classId: id });
        if (studentCount > 0) {
            throw new common_1.BadRequestException(`Cannot delete class: ${studentCount} student(s) are assigned to this class. Please reassign or delete them first.`);
        }
        const classDoc = await this.classModel.findByIdAndDelete(id).lean();
        return (0, mongo_serializer_1.toJSON)(classDoc);
    }
    async findNextClass(id) {
        const cur = await this.classModel.findById(id).lean();
        if (!cur)
            return null;
        if (cur.order === undefined || cur.order === null)
            return null;
        const nextClass = await this.classModel
            .findOne({ order: { $gt: cur.order } })
            .sort({ order: 1 })
            .lean();
        return (0, mongo_serializer_1.toJSON)(nextClass);
    }
};
exports.ClassesService = ClassesService;
exports.ClassesService = ClassesService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, mongoose_1.InjectModel)(class_schema_1.Class.name)),
    __param(1, (0, mongoose_1.InjectModel)(section_schema_1.Section.name)),
    __param(2, (0, mongoose_1.InjectModel)(student_schema_1.Student.name)),
    __metadata("design:paramtypes", [mongoose_2.Model,
        mongoose_2.Model,
        mongoose_2.Model])
], ClassesService);
//# sourceMappingURL=classes.service.js.map