'use strict'; const marketplaceService = require('../services/marketplace.service'); const asyncHandler = (fn) => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; const checkout = asyncHandler(async (req, res) => { const userId = req.user.id || req.user.sub; const { productId, quantity, shippingAddress } = req.body; if (!productId || !quantity || !shippingAddress) { return res.status(400).json({ error: { message: 'Missing required order fields' } }); } try { const order = await marketplaceService.placeOrder(userId, productId, quantity, shippingAddress); res.status(201).json({ data: order }); } catch (err) { res.status(400).json({ error: { message: err.message } }); } }); const getHistory = asyncHandler(async (req, res) => { const userId = req.user.id || req.user.sub; const orders = await marketplaceService.listUserOrders(userId); res.json({ data: orders }); }); const getProviderOrders = asyncHandler(async (req, res) => { const userId = req.user.id || req.user.sub; // Get provider profile first const pool = require('../db').getPool(); const profileRes = await pool.query('SELECT id FROM provider_profiles WHERE user_id = $1', [userId]); if (profileRes.rows.length === 0) { return res.status(404).json({ error: { message: 'Provider profile not found' } }); } const orders = await marketplaceService.listProviderOrders(profileRes.rows[0].id); res.json({ data: orders }); }); const updateStatus = asyncHandler(async (req, res) => { const userId = req.user.id || req.user.sub; const { status } = req.body; const { id } = req.params; // Get provider profile first const pool = require('../db').getPool(); const profileRes = await pool.query('SELECT id FROM provider_profiles WHERE user_id = $1', [userId]); if (profileRes.rows.length === 0) { return res.status(404).json({ error: { message: 'Provider profile not found' } }); } const order = await marketplaceService.updateOrderStatus(id, status, profileRes.rows[0].id); res.json({ data: order }); }); module.exports = { checkout, getHistory, getProviderOrders, updateStatus };