'use strict'; const express = require('express'); const { models } = require('../../core/db'); const { authenticateToken, authenticateRole } = require('../../core/auth'); const { ok, created, collection, noContent } = require('../../core/respond'); const { AppError } = require('../../core/errors'); const { createWorkout: createWorkoutSchema, updateWorkout: updateWorkoutSchema } = require('../../core/schemas/workouts'); const svc = require('./service'); const router = express.Router(); router.prefix = 'workouts'; const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin']; function validate(schema) { return (req, res, next) => { const result = schema.safeParse(req.body); if (!result.success) { const e = result.error.errors[0]; return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0])); } req.body = result.data; next(); }; } router.get('/today', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { try { const workouts = await svc.getTodayWorkouts(models, req.user.organizationId); ok(res, workouts); } catch (err) { next(err); } }); router.get('/', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { try { const { page = 1, limit = 20 } = req.query; const { rows, count } = await svc.getWorkouts(models, req.user.organizationId, { page: +page, limit: +limit }); collection(res, rows, count, +page, +limit); } catch (err) { next(err); } }); router.post('/', authenticateToken, authenticateRole(COACH_PLUS), validate(createWorkoutSchema), async (req, res, next) => { try { const workout = await svc.createWorkout(models, req, req.user.organizationId, req.body); created(res, workout); } catch (err) { next(err); } }); router.get('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { try { const workout = await svc.getWorkoutById(models, parseInt(req.params.id, 10), req.user.organizationId); ok(res, workout); } catch (err) { next(err); } }); router.patch('/:id', authenticateToken, authenticateRole(COACH_PLUS), validate(updateWorkoutSchema), async (req, res, next) => { try { const workout = await svc.updateWorkout(models, req, parseInt(req.params.id, 10), req.user.organizationId, req.body); ok(res, workout); } catch (err) { next(err); } }); router.delete('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { try { await svc.deleteWorkout(models, req, parseInt(req.params.id, 10), req.user.organizationId); noContent(res); } catch (err) { next(err); } }); module.exports = router;