const couchdbService = require("../services/couchdbService"); class UserBadge { static async create(userBadgeData) { const doc = { type: "user_badge", ...userBadgeData, earnedAt: userBadgeData.earnedAt || new Date().toISOString(), progress: userBadgeData.progress || 0, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), }; return await couchdbService.createDocument(doc); } static async findById(id) { const doc = await couchdbService.getDocument(id); if (doc && doc.type === "user_badge") { return doc; } return null; } static async find(filter = {}) { const selector = { type: "user_badge", ...filter, }; return await couchdbService.findDocuments(selector); } static async findByUser(userId) { const selector = { type: "user_badge", userId: userId, }; const userBadges = await couchdbService.findDocuments(selector); // Populate badge data for each user badge const populatedBadges = await Promise.all( userBadges.map(async (userBadge) => { if (userBadge.badgeId) { const badge = await couchdbService.getDocument(userBadge.badgeId); return { ...userBadge, badge: badge, }; } return userBadge; }) ); return populatedBadges; } static async findByBadge(badgeId) { const selector = { type: "user_badge", badgeId: badgeId, }; return await couchdbService.findDocuments(selector); } static async update(id, updateData) { const doc = await couchdbService.getDocument(id); if (!doc || doc.type !== "user_badge") { throw new Error("UserBadge not found"); } const updatedDoc = { ...doc, ...updateData, updatedAt: new Date().toISOString(), }; return await couchdbService.updateDocument(id, updatedDoc); } static async delete(id) { const doc = await couchdbService.getDocument(id); if (!doc || doc.type !== "user_badge") { throw new Error("UserBadge not found"); } return await couchdbService.deleteDocument(id, doc._rev); } static async findByUserAndBadge(userId, badgeId) { const selector = { type: "user_badge", userId: userId, badgeId: badgeId, }; const results = await couchdbService.findDocuments(selector); return results[0] || null; } static async updateProgress(userId, badgeId, progress) { const userBadge = await this.findByUserAndBadge(userId, badgeId); if (userBadge) { return await this.update(userBadge._id, { progress }); } else { return await this.create({ userId, badgeId, progress, }); } } } module.exports = UserBadge;