'use strict'; const { Op } = require('sequelize'); const { DateTime } = require('luxon'); const { AppError } = require('../../core/errors'); const { log: auditLog } = require('../../core/audit'); const STREAM_BASE = '/api/v1/videos/stream/'; function videoIncludes(models) { return [ { model: models.Video, as: 'VideoOne', required: false, attributes: ['id', 'description', 'filename', 'category'] }, { model: models.Video, as: 'VideoTwo', required: false, attributes: ['id', 'description', 'filename', 'category'] }, { model: models.Video, as: 'VideoThree', required: false, attributes: ['id', 'description', 'filename', 'category'] }, { model: models.Video, as: 'VideoFour', required: false, attributes: ['id', 'description', 'filename', 'category'] }, ]; } function formatWorkout(w) { const obj = w.toJSON(); obj.videos = [ { slot: 1, video: obj.VideoOne ? { ...obj.VideoOne, streamUrl: STREAM_BASE + obj.VideoOne.filename } : null, reps: obj.number1 }, { slot: 2, video: obj.VideoTwo ? { ...obj.VideoTwo, streamUrl: STREAM_BASE + obj.VideoTwo.filename } : null, reps: obj.number2 }, { slot: 3, video: obj.VideoThree ? { ...obj.VideoThree, streamUrl: STREAM_BASE + obj.VideoThree.filename } : null, reps: obj.number3 }, { slot: 4, video: obj.VideoFour ? { ...obj.VideoFour, streamUrl: STREAM_BASE + obj.VideoFour.filename } : null, reps: obj.number4 }, ].filter(s => s.video || s.reps); delete obj.VideoOne; delete obj.VideoTwo; delete obj.VideoThree; delete obj.VideoFour; return obj; } async function getWorkouts(models, orgId, { page = 1, limit = 20 } = {}) { const offset = (page - 1) * limit; const { rows, count } = await models.Workout.findAndCountAll({ where: { organizationId: orgId }, include: videoIncludes(models), limit, offset, order: [['workoutDate', 'DESC'], ['createdAt', 'DESC']], }); return { rows: rows.map(formatWorkout), count }; } async function getWorkoutById(models, id, orgId) { const w = await models.Workout.findOne({ where: { id, organizationId: orgId }, include: videoIncludes(models), }); if (!w) throw new AppError('NOT_FOUND', 'Workout not found.', 404); return formatWorkout(w); } async function getTodayWorkouts(models, orgId) { const org = await models.Organization.findByPk(orgId, { attributes: ['timezone'] }); const tz = org?.timezone || 'UTC'; const now = DateTime.now().setZone(tz); const start = now.startOf('day').toUTC().toJSDate(); const end = now.endOf('day').toUTC().toJSDate(); const rows = await models.Workout.findAll({ where: { organizationId: orgId, workoutDate: { [Op.between]: [start, end] } }, include: videoIncludes(models), order: [['workoutDate', 'ASC']], }); return rows.map(formatWorkout); } async function createWorkout(models, req, orgId, data) { // Validate video IDs belong to org for (const slot of [1, 2, 3, 4]) { const vid = data[`video${slot}`]; if (vid) { const exists = await models.Video.findOne({ where: { id: vid, organizationId: orgId } }); if (!exists) throw new AppError('VALIDATION_FAILED', `Video ${vid} not found in your library.`, 400, `video${slot}`); } } const workout = await models.Workout.create({ ...data, organizationId: orgId, createdByUserId: req.user.id }); await auditLog(req, 'workout.create', 'workout', workout.id, { name: data.name }); return getWorkoutById(models, workout.id, orgId); } async function deleteWorkout(models, req, id, orgId) { const workout = await models.Workout.findOne({ where: { id, organizationId: orgId } }); if (!workout) throw new AppError('NOT_FOUND', 'Workout not found.', 404); if (req.user.role === 'Coach' && workout.createdByUserId !== req.user.id) { throw new AppError('AUTH_FORBIDDEN', 'You can only delete your own workouts.', 403); } await auditLog(req, 'workout.delete', 'workout', id, { name: workout.name }); await workout.destroy(); } module.exports = { getWorkouts, getWorkoutById, getTodayWorkouts, createWorkout, deleteWorkout };