'use strict'; const { AppError } = require('../../core/errors'); const { log: auditLog } = require('../../core/audit'); const { getIo } = require('../../core/socket'); const TimerEngine = require('./timer-engine'); // Active sessions: sessionId → { engine, orgId } const activeSessions = new Map(); async function getTimers(models, orgId) { return models.Timer.findAll({ where: { organizationId: orgId }, order: [['createdAt', 'DESC']] }); } async function getTimerById(models, id, orgId) { const timer = await models.Timer.findOne({ where: { id, organizationId: orgId } }); if (!timer) throw new AppError('NOT_FOUND', 'Timer not found.', 404); return timer; } async function createTimer(models, req, orgId, data) { const timer = await models.Timer.create({ ...data, organizationId: orgId, createdByUserId: req.user.id }); await auditLog(req, 'timer.create', 'timer', timer.id, { name: data.name }); return timer; } async function deleteTimer(models, req, id, orgId) { const timer = await getTimerById(models, id, orgId); if (req.user.role === 'Coach' && timer.createdByUserId !== req.user.id) { throw new AppError('AUTH_FORBIDDEN', 'You can only delete your own timers.', 403); } // Stop active session if one exists for this timer for (const [sessionId, session] of activeSessions) { if (session.orgId === orgId && sessionId.startsWith(`timer_${id}_`)) { session.engine.stop(); activeSessions.delete(sessionId); } } await auditLog(req, 'timer.delete', 'timer', id, { name: timer.name }); await timer.destroy(); } async function launchTimer(models, req, timerId, orgId) { const timer = await getTimerById(models, timerId, orgId); const io = getIo(); const sessionId = `timer_${timerId}_${Date.now()}`; const engine = new TimerEngine(timer.toJSON(), io, sessionId); activeSessions.set(sessionId, { engine, orgId }); engine.start(); await auditLog(req, 'timer.launch', 'timer', timerId, { sessionId }); return { sessionId }; } async function stopTimer(req, sessionId, orgId) { const session = activeSessions.get(sessionId); if (!session || session.orgId !== orgId) { throw new AppError('NOT_FOUND', 'Active timer session not found.', 404); } session.engine.stop(); activeSessions.delete(sessionId); await auditLog(req, 'timer.stop', null, null, { sessionId }); } function getActiveSession(orgId) { for (const [sessionId, session] of activeSessions) { if (session.orgId === orgId) { return { sessionId, state: session.engine.getState() }; } } return null; } function getSessionEngine(sessionId) { return activeSessions.get(sessionId)?.engine ?? null; } module.exports = { getTimers, getTimerById, createTimer, deleteTimer, launchTimer, stopTimer, getActiveSession, getSessionEngine };