const DeviceService = require('../services/device.service'); const { deviceSchema, deviceUpdateSchema } = require('../helpers/validation'); const { setResponse } = require('../helpers/utils'); class DeviceController { // Get all devices static async getAll(req, res) { try { const { search } = req.query; const devices = await DeviceService.getAllDevices(search || ''); return res.status(200).json(setResponse(devices, 'Devices retrieved successfully', 200)); } catch (err) { return res.status(err.statusCode || 500).json( setResponse([], err.message || 'Failed to retrieve devices', err.statusCode || 500) ); } } // Get device by ID static async getById(req, res) { try { const { id } = req.params; const device = await DeviceService.getDeviceById(id); return res.status(200).json(setResponse(device, 'Device retrieved successfully', 200)); } catch (err) { return res.status(err.statusCode || 500).json( setResponse([], err.message || 'Device not found', err.statusCode || 500) ); } } // Create device static async create(req, res) { try { const { error, value } = deviceSchema.validate(req.body || {}, { abortEarly: false }); if (error) { const errors = error.details.reduce((acc, cur) => { const field = Array.isArray(cur.path) ? cur.path.join('.') : String(cur.path); if (!acc[field]) acc[field] = []; acc[field].push(cur.message); return acc; }, {}); return res.status(400).json(setResponse(errors, 'Validation failed', 400)); } const newDevice = await DeviceService.createDevice(value, req.user.user_id); return res.status(201).json( setResponse(newDevice, 'Device created successfully', 201) ); } catch (err) { return res.status(err.statusCode || 500).json( setResponse([], err.message || 'Failed to create device', err.statusCode || 500) ); } } // Update device static async update(req, res) { try { const { id } = req.params; const { error, value } = deviceUpdateSchema.validate(req.body || {}, { abortEarly: false }); if (error) { const errors = error.details.reduce((acc, cur) => { const field = Array.isArray(cur.path) ? cur.path.join('.') : String(cur.path); if (!acc[field]) acc[field] = []; acc[field].push(cur.message); return acc; }, {}); return res.status(400).json(setResponse(errors, 'Validation failed', 400)); } const updatedDevice = await DeviceService.updateDevice(id, value, req.user.user_Id); return res.status(200).json( setResponse(updatedDevice.data, 'Device updated successfully', 200) ); } catch (err) { return res.status(err.statusCode || 500).json( setResponse([], err.message || 'Failed to update device', err.statusCode || 500) ); } } // Soft delete device static async delete(req, res) { try { const { id } = req.params; await DeviceService.deleteDevice(id, req.user.userId); return res.status(200).json( setResponse([], 'Device deleted successfully', 200) ); } catch (err) { return res.status(err.statusCode || 500).json( setResponse([], err.message || 'Failed to delete device', err.statusCode || 500) ); } } } module.exports = DeviceController;