"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MongooseSupportAgentRepository = void 0;
const SupportAgentModel_js_1 = require("../models/SupportAgentModel.js");
class MongooseSupportAgentRepository {
    async findById(id) {
        const doc = await SupportAgentModel_js_1.SupportAgentModel.findById(id).lean();
        return doc ? this.mapDocument(doc) : null;
    }
    async findByAdminUserId(adminUserId) {
        const doc = await SupportAgentModel_js_1.SupportAgentModel.findOne({ adminUserId }).lean();
        return doc ? this.mapDocument(doc) : null;
    }
    async findActive() {
        const docs = await SupportAgentModel_js_1.SupportAgentModel.find({ active: true }).lean();
        return docs.map((doc) => this.mapDocument(doc));
    }
    async findOnline() {
        const docs = await SupportAgentModel_js_1.SupportAgentModel.find({ active: true, online: true }).lean();
        return docs.map((doc) => this.mapDocument(doc));
    }
    async findAll() {
        const docs = await SupportAgentModel_js_1.SupportAgentModel.find().sort({ createdAt: -1 }).lean();
        return docs.map((doc) => this.mapDocument(doc));
    }
    async create(input) {
        const doc = await SupportAgentModel_js_1.SupportAgentModel.create(input);
        return this.mapDocument(doc.toObject());
    }
    async update(id, input) {
        const doc = await SupportAgentModel_js_1.SupportAgentModel.findByIdAndUpdate(id, input, { new: true }).lean();
        return doc ? this.mapDocument(doc) : null;
    }
    async updateCurrentTickets(id, delta) {
        const doc = await SupportAgentModel_js_1.SupportAgentModel.findByIdAndUpdate(id, [{ $set: { currentTickets: { $max: [0, { $sum: ["$currentTickets", delta] }] } } }], { new: true, updatePipeline: true }).lean();
        return doc ? this.mapDocument(doc) : null;
    }
    async delete(id) {
        const result = await SupportAgentModel_js_1.SupportAgentModel.findByIdAndDelete(id);
        return result !== null;
    }
    mapDocument(doc) {
        return {
            id: doc._id.toString(),
            adminUserId: doc.adminUserId,
            displayName: doc.displayName,
            active: doc.active,
            online: doc.online,
            status: doc.status,
            maxConcurrentTickets: doc.maxConcurrentTickets,
            currentTickets: doc.currentTickets,
            role: doc.role,
            createdAt: doc.createdAt,
            updatedAt: doc.updatedAt
        };
    }
}
exports.MongooseSupportAgentRepository = MongooseSupportAgentRepository;
