const MatrixRepository = require('../../repositories/matrix/MatrixRepository'); const Matrix = require('../../models/Matrix'); function isAdmin(user) { return !!user && ['admin', 'super_admin'].includes(user.role); } function isValidEmail(s) { return typeof s === 'string' && /\S+@\S+\.\S+/.test(s); } async function create({ name, topNodeEmail, force = false, actorUser }) { if (!actorUser) { const err = new Error('Unauthorized'); err.status = 401; throw err; } if (!isAdmin(actorUser)) { const err = new Error('Forbidden: Admins only'); err.status = 403; throw err; } const trimmedName = (name || '').trim(); if (!trimmedName) { const err = new Error('Matrix name is required'); err.status = 400; throw err; } if (trimmedName.length > 255) { const err = new Error('Matrix name is too long'); err.status = 400; throw err; } const email = (topNodeEmail || '').trim().toLowerCase(); if (!isValidEmail(email)) { const err = new Error('Valid top node email is required'); err.status = 400; throw err; } const res = await MatrixRepository.createMatrix({ name: trimmedName, topNodeEmail: email, force }); return new Matrix({ name: res.name, masterTopUserId: res.masterTopUserId, masterTopUserEmail: res.masterTopUserEmail }); } async function getStats({ actorUser }) { if (!actorUser) { const err = new Error('Unauthorized'); err.status = 401; throw err; } if (!isAdmin(actorUser)) { const err = new Error('Forbidden: Admins only'); err.status = 403; throw err; } const stats = await MatrixRepository.getMatrixStats(); // Keep the response shape straightforward for the dashboard return { activeMatrices: stats.activeMatrices, totalMatrices: stats.totalMatrices, totalUsersSubscribed: stats.totalUsersSubscribed, matrices: stats.matrices.map(m => ({ rootUserId: m.rootUserId, name: m.name, isActive: !!m.isActive, usersCount: m.usersCount, createdAt: m.createdAt, // equals ego_activated_at topNodeEmail: m.topNodeEmail })) }; } module.exports = { create, getStats };