/** * Complaint Controller - Admin Resolution of User Issues (PostgreSQL) */ const { getPool } = require('../db'); const { eventBus, EVENTS } = require('../services/eventBus'); /** * List all complaints in the system */ async function list(req, res) { const { status, limit = 50, offset = 0 } = req.query; const pool = getPool(); if (!pool) return res.status(500).json({ error: 'Database not connected' }); try { let query = 'SELECT c.*, u.name as user_name FROM complaints c JOIN users u ON c.user_id = u.id WHERE 1=1'; const params = []; let paramCounter = 1; if (status) { query += ` AND c.status = $${paramCounter++}`; params.push(status); } query += ` ORDER BY c.created_at DESC LIMIT $${paramCounter++} OFFSET $${paramCounter++}`; params.push(parseInt(limit), parseInt(offset)); const result = await pool.query(query, params); res.json({ success: true, count: result.rows.length, data: result.rows }); } catch (error) { console.error('[Complaint List Error]', error.message); res.status(500).json({ error: 'Failed to fetch complaints' }); } } /** * Get complaint by ID */ async function show(req, res) { const { id } = req.params; const pool = getPool(); if (!pool) return res.status(500).json({ error: 'Database not connected' }); try { const query = 'SELECT c.*, u.name as user_name, u.email as user_email FROM complaints c JOIN users u ON c.user_id = u.id WHERE c.id = $1'; const result = await pool.query(query, [id]); if (result.rows.length === 0) { return res.status(404).json({ error: 'Complaint not found' }); } res.json({ success: true, data: result.rows[0] }); } catch (error) { console.error('[Complaint Get Error]', error.message); res.status(500).json({ error: 'Failed to fetch complaint' }); } } /** * Update complaint status (Resolve) */ async function update(req, res) { const { id } = req.params; const { status, resolution } = req.body; const pool = getPool(); if (!pool) return res.status(500).json({ error: 'Database not connected' }); try { const query = 'UPDATE complaints SET status = $2, resolution = $3, updated_at = NOW() WHERE id = $1'; await pool.query(query, [id, status, resolution || '']); if (status === 'resolved') { eventBus.emit(EVENTS.COMPLAINT_RESOLVED, { complaint_id: id }); } res.json({ success: true, message: `Complaint status updated to ${status}` }); } catch (error) { console.error('[Complaint Update Error]', error.message); res.status(500).json({ error: 'Failed to update complaint' }); } } module.exports = { list, show, update };