import { Injectable } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; import { FilterQuery, Model, Types } from "mongoose"; import { RegisterDto } from "src/auth/dto/actor/register.actor.dto"; import { ExpertModel } from "src/users/entities/schema/expert.schema"; import { DamageExpertModel } from "../schema/damage-expert.schema"; import { UserModel } from "../schema/user.schema"; @Injectable() export class DamageExpertDbService { constructor( @InjectModel(DamageExpertModel.name) private readonly damageExpertModel: Model, ) {} async create(user: RegisterDto): Promise { return await this.damageExpertModel.create(user); } async findOne(user: FilterQuery): Promise { return await this.damageExpertModel.findOne(user); } async findById(userId: string): Promise { return await this.damageExpertModel.findOne({ _id: new Types.ObjectId(userId), }); } async findOneAndUpdate( user: FilterQuery, update: FilterQuery, ): Promise { return await this.damageExpertModel.findOneAndUpdate(user, update); } async findAll( filter: FilterQuery, ): Promise<(DamageExpertModel & { _id: Types.ObjectId })[]> { return await this.damageExpertModel.find(filter).lean(); } async findAndUpdate(filter: any, update: any): Promise { return this.damageExpertModel .findOneAndUpdate(filter, update, { new: true }) .exec(); } async updateStats( expertId: string, type: "checked" | "handled", requestId: string, ) { if (!expertId || !requestId || !["checked", "handled"].includes(type)) { console.warn("Invalid expertId, requestId, or type"); return; } const expert = await this.damageExpertModel.findById(expertId); if (!expert) { console.warn("Expert not found:", expertId); return; } const requestIdStr = new Types.ObjectId(requestId).toString(); const countedRequests = expert.countedRequests?.map((r) => r.toString()) || []; if (type === "checked" && countedRequests.includes(requestIdStr)) { console.log( `Request ${requestIdStr} already checked for expert ${expertId}`, ); return; } const update: any = { $inc: {}, $push: {} }; if (type === "checked") { update.$inc["requestStats.totalChecked"] = 1; update.$push["countedRequests"] = requestIdStr; } else if (type === "handled") { update.$inc["requestStats.totalHandled"] = 1; if (countedRequests.includes(requestIdStr)) { update.$inc["requestStats.totalChecked"] = -1; } if (!countedRequests.includes(requestIdStr)) { update.$push["countedRequests"] = requestIdStr; } else { delete update.$push; } } const result = await this.damageExpertModel.findByIdAndUpdate( expertId, update, ); if (!result) { console.warn("Failed to update stats for expert:", expertId); } else { console.log(`Stats updated (${type}) for expert:`, expertId); } } async updateOne(filter: any, update: any) { return this.damageExpertModel.updateOne(filter, update); } }