const { getAllDevicesDb, getDeviceByIdDb, getDeviceByCodeDb, createDeviceDb, updateDeviceDb, softDeleteDeviceDb, searchDevicesDb } = require('../db/device.db'); const { ErrorHandler } = require('../helpers/error'); class DeviceService { // Get all devices static async getAllDevices(search) { if (!search || search.trim() === '') { return await getAllDevicesDb(); } return await searchDevicesDb(search); } // Get device by ID static async getDeviceById(id) { const device = await getDeviceByIdDb(id); if (!device) throw new ErrorHandler(404, 'Device not found'); return device; } // Get device by code static async getDeviceByCode(code) { const device = await getDeviceByCodeDb(code); if (!device) throw new ErrorHandler(404, 'Device not found'); return device; } // Create device static async createDevice(data, userId) { if (!data || typeof data !== 'object') data = {}; data.created_by = userId; // Cek kode unik const existingDevice = await getDeviceByCodeDb(data.device_code); if (existingDevice) { throw new ErrorHandler(400, 'Device code already exists'); } const newDevice = await createDeviceDb(data); return newDevice; } // Update device static async updateDevice(id, data, userId) { if (!data || typeof data !== 'object') data = {}; const existingDevice = await getDeviceByIdDb(id); if (!existingDevice) { throw new ErrorHandler(404, 'Device not found'); } data.updated_by = userId; const updatedDevice = await updateDeviceDb(id, data); return { message: 'Device updated successfully', data: updatedDevice, }; } // Soft delete device static async deleteDevice(id, userId) { const existingDevice = await getDeviceByIdDb(id); if (!existingDevice) { throw new ErrorHandler(404, 'Device not found'); } await softDeleteDeviceDb(id, userId); return { message: 'Device deleted successfully' }; } } module.exports = DeviceService;