"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MongooseSupportTicketRepository = void 0;
const SupportTicketModel_js_1 = require("../models/SupportTicketModel.js");
class MongooseSupportTicketRepository {
    async findById(id) {
        const doc = await SupportTicketModel_js_1.SupportTicketModel.findById(id).lean();
        return doc ? this.mapDocument(doc) : null;
    }
    async findByTicketNumber(ticketNumber) {
        const doc = await SupportTicketModel_js_1.SupportTicketModel.findOne({ ticketNumber }).lean();
        return doc ? this.mapDocument(doc) : null;
    }
    async findOpenByUserId(userId) {
        const doc = await SupportTicketModel_js_1.SupportTicketModel.findOne({
            userId,
            status: { $nin: ["CLOSED", "RESOLVED"] }
        }).lean();
        return doc ? this.mapDocument(doc) : null;
    }
    async findByUserId(userId, limit = 50) {
        const docs = await SupportTicketModel_js_1.SupportTicketModel.find({ userId })
            .sort({ createdAt: -1 })
            .limit(limit)
            .lean();
        return docs.map((doc) => this.mapDocument(doc));
    }
    async findAll(filters, sort, skip = 0, limit = 50) {
        const query = this.buildQuery(filters);
        const sortOption = this.buildSort(sort);
        const docs = await SupportTicketModel_js_1.SupportTicketModel.find(query)
            .sort(sortOption)
            .skip(skip)
            .limit(limit)
            .lean();
        return docs.map((doc) => this.mapDocument(doc));
    }
    async count(filters) {
        const query = this.buildQuery(filters);
        return SupportTicketModel_js_1.SupportTicketModel.countDocuments(query);
    }
    async create(input) {
        const doc = await SupportTicketModel_js_1.SupportTicketModel.create(input);
        return this.mapDocument(doc.toObject());
    }
    async update(id, input) {
        const update = { ...input };
        if (update.status)
            update.status = String(update.status).toUpperCase();
        if (update.priority)
            update.priority = String(update.priority).toUpperCase();
        const doc = await SupportTicketModel_js_1.SupportTicketModel.findByIdAndUpdate(id, { $set: update }, { new: true }).lean();
        return doc ? this.mapDocument(doc) : null;
    }
    async updateAtomic(id, input, expectedVersion) {
        const query = { _id: id };
        if (expectedVersion) {
            query.updatedAt = expectedVersion;
        }
        const setValues = { ...input, updatedAt: new Date() };
        if (input.status === "CLOSED" || input.status === "RESOLVED") {
            setValues.closedAt = new Date();
        }
        const update = { $set: setValues };
        const doc = await SupportTicketModel_js_1.SupportTicketModel.findOneAndUpdate(query, update, { new: true }).lean();
        return doc ? this.mapDocument(doc) : null;
    }
    async delete(id) {
        const result = await SupportTicketModel_js_1.SupportTicketModel.findByIdAndDelete(id);
        return result !== null;
    }
    buildQuery(filters) {
        const query = {};
        if (!filters)
            return query;
        if (filters.status) {
            query.status = Array.isArray(filters.status) ? { $in: filters.status } : filters.status;
        }
        if (filters.priority) {
            query.priority = Array.isArray(filters.priority) ? { $in: filters.priority } : filters.priority;
        }
        if (filters.category)
            query.category = filters.category;
        if (filters.assignedAgent)
            query.assignedAgent = filters.assignedAgent;
        if (filters.userId)
            query.userId = filters.userId;
        if (filters.search) {
            query.$or = [
                { ticketNumber: { $regex: filters.search, $options: "i" } },
                { lastMessage: { $regex: filters.search, $options: "i" } }
            ];
        }
        return query;
    }
    buildSort(sort) {
        if (!sort)
            return { lastActivity: -1 };
        return { [sort.field]: sort.direction === "asc" ? 1 : -1 };
    }
    mapDocument(doc) {
        return {
            id: doc._id.toString(),
            ticketNumber: doc.ticketNumber,
            userId: doc.userId,
            status: doc.status,
            priority: doc.priority,
            assignedAgent: doc.assignedAgent,
            category: doc.category,
            lastMessage: doc.lastMessage,
            lastActivity: doc.lastActivity,
            createdAt: doc.createdAt,
            updatedAt: doc.updatedAt,
            closedAt: doc.closedAt
        };
    }
}
exports.MongooseSupportTicketRepository = MongooseSupportTicketRepository;
