import { ApiError } from '../../common/errors/ApiError.js'; import { asyncHandler } from '../../common/middleware/asyncHandler.js'; import { getPagination, paginated } from '../../common/utils/pagination.js'; import { created, ok } from '../../common/utils/response.js'; import { subscriptionsRepository } from './subscriptions.repository.js'; import { subscriptionsService } from './subscriptions.service.js'; export const subscriptionsController = { listPlans: asyncHandler(async (req, res) => ok(res, await subscriptionsRepository.listPlans(req.gymId))), createPlan: asyncHandler(async (req, res) => created(res, await subscriptionsRepository.createPlan(req.gymId, req.body), 'Plan created')), updatePlan: asyncHandler(async (req, res) => ok(res, await subscriptionsRepository.updatePlan(req.gymId, req.params.id, req.body), 'Plan updated')), deletePlan: asyncHandler(async (req, res) => { await subscriptionsRepository.deletePlan(req.gymId, req.params.id); ok(res, null, 'Plan deleted'); }), list: asyncHandler(async (req, res) => { const pagination = getPagination(req.query); const [items, total] = await subscriptionsRepository.list({ gymId: req.gymId, search: req.query.search, ...pagination }); ok(res, paginated(items, total, pagination.page, pagination.limit)); }), mySubscriptions: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); ok(res, await subscriptionsRepository.findForMember(req.gymId, req.user.memberId)); }), expiring: asyncHandler(async (req, res) => { const days = Number(req.query.days || 7); ok(res, await subscriptionsRepository.expiring(req.gymId, days), 'Expiring subscriptions'); }), purchase: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); created(res, await subscriptionsService.purchaseForMember(req.gymId, req.user.memberId, req.body), 'Membership request submitted'); }), get: asyncHandler(async (req, res) => { const subscription = await subscriptionsRepository.findById(req.gymId, req.params.id); if (!subscription) throw ApiError.notFound('Subscription not found'); ok(res, subscription); }), assign: asyncHandler(async (req, res) => created(res, await subscriptionsService.assign(req.gymId, req.body), 'Subscription assigned')), renew: asyncHandler(async (req, res) => ok(res, await subscriptionsService.renew(req.gymId, req.params.id, req.body), 'Subscription renewed')), freeze: asyncHandler(async (req, res) => ok(res, await subscriptionsService.freeze(req.gymId, req.params.id, req.body.freezeDays), 'Subscription frozen')), expireOld: asyncHandler(async (req, res) => ok(res, await subscriptionsRepository.expireOld(req.gymId), 'Expired subscriptions updated')), };