const express = require('express'); const { authenticateAPIKey, verifyToken } = require('../auth'); const { listGraphsBalanceHistory, listStock, removeGraphsBalance, saveGraphsBalance, upsertStockItems } = require('../services/stockService'); const router = express.Router(); router.get('/stock', verifyToken, async (req, res) => { try { res.json(await listStock()); } catch (error) { console.error('Error fetching stock:', error); res.status(500).json({ error: 'Internal Server Error' }); } }); router.get('/stock/:productId/graphs-balance-history', verifyToken, async (req, res) => { try { res.json(await listGraphsBalanceHistory(req.params.productId)); } catch (error) { console.error('Error fetching Graphs stock balance history:', error); res.status(500).json({ error: 'Internal Server Error' }); } }); router.put('/stock/:productId/graphs-balance', verifyToken, async (req, res) => { try { const balance = await saveGraphsBalance(req.params.productId, req.body, req.user?.email); res.json(balance); } catch (error) { console.error('Error saving Graphs stock balance:', error); res.status(error.statusCode || 500).json({ error: error.message || 'Internal Server Error' }); } }); router.delete('/stock/:productId/graphs-balance', verifyToken, async (req, res) => { try { const balance = await removeGraphsBalance(req.params.productId, req.user?.email); res.json(balance); } catch (error) { console.error('Error removing Graphs stock balance:', error); res.status(error.statusCode || 500).json({ error: error.message || 'Internal Server Error' }); } }); router.post('/stock', authenticateAPIKey, async (req, res) => { res.status(201).json({ message: 'Stock data received, processing in background' }); const payload = Array.isArray(req.body) ? req.body : [req.body]; upsertStockItems(payload).catch((error) => { console.error('Database stock insert error:', error); }); }); module.exports = router;