'use strict'; const bookingService = require('../services/booking.service'); const asyncHandler = (fn) => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; const create = asyncHandler(async (req, res) => { const userId = req.user.sub || req.user.id; const booking = await bookingService.createBooking({ userId, serviceId: req.body.serviceId, scheduledAt: req.body.scheduledAt, endTime: req.body.endTime, details: req.body.details }); res.status(201).json({ data: booking }); }); const checkAvailability = asyncHandler(async (req, res) => { const { serviceId } = req.params; const { startTime, endTime } = req.query; if (!startTime || !endTime) { return res.status(400).json({ error: { message: 'startTime and endTime query parameters are required' } }); } const availability = await bookingService.checkAvailability(serviceId, startTime, endTime); res.json({ data: availability }); }); const list = asyncHandler(async (req, res) => { const { status, limit, offset } = req.query; const userId = req.user.sub || req.user.id; const bookings = await bookingService.listBookings(userId, { status, limit: parseInt(limit) || 50, offset: parseInt(offset) || 0 }); res.json({ data: bookings }); }); const getById = asyncHandler(async (req, res) => { const booking = await bookingService.getBookingById(req.params.id); if (!booking) { return res.status(404).json({ error: { message: 'Booking not found' } }); } const userId = req.user.sub || req.user.id; if (booking.user_id !== userId && req.user.role !== 'admin') { return res.status(403).json({ error: { message: 'Not authorized' } }); } res.json({ data: booking }); }); const updateStatus = asyncHandler(async (req, res) => { const { status } = req.body; const booking = await bookingService.updateBookingStatus(req.params.id, status); res.json({ data: booking }); }); const cancel = asyncHandler(async (req, res) => { const userId = req.user.sub || req.user.id; const booking = await bookingService.cancelBooking(req.params.id, userId); res.json({ data: booking }); }); const listProviderBookings = asyncHandler(async (req, res) => { const userId = req.user.sub || req.user.id; const providerProfile = await bookingService.getProviderProfile(userId); if (!providerProfile) { return res.status(404).json({ error: { message: 'Provider profile not found' } }); } const { status, limit, offset } = req.query; const bookings = await bookingService.listProviderBookings(providerProfile.id, { status, limit: parseInt(limit) || 50, offset: parseInt(offset) || 0 }); res.json({ data: bookings }); }); module.exports = { create, list, getById, updateStatus, cancel, checkAvailability, listProviderBookings };