const {
  getAllDevicesDb,
  getDeviceByIdDb,
  createDeviceDb,
  updateDeviceDb,
  deleteDeviceDb
} = require('../db/device.db');
const { ErrorHandler } = require('../helpers/error');

class DeviceService {
  // Get all devices
  static async getAllDevices(param) {
    try {
      const results = await getAllDevicesDb(param);

      results.data.map(element => {
      });

      return results
    } catch (error) {
      throw new ErrorHandler(error.statusCode, error.message);
    }
  }

  // Get device by ID
  static async getDeviceById(id) {
    try {
      const result = await getDeviceByIdDb(id);

      if (result.length < 1) throw new ErrorHandler(404, 'Device not found');

      return result;
    } catch (error) {
      throw new ErrorHandler(error.statusCode, error.message);
    }
  }

  // Create device
  static async createDevice(data) {
    try {
      if (!data || typeof data !== 'object') data = {};

      const result = await createDeviceDb(data);

      return result;
    } catch (error) {
      throw new ErrorHandler(error.statusCode, error.message);
    }
  }

  // Update device
  static async updateDevice(id, data) {
    try {
      if (!data || typeof data !== 'object') data = {};

      const dataExist = await getDeviceByIdDb(id);

      if (dataExist.length < 1) {
        throw new ErrorHandler(404, 'Device not found');
      }

      const result = await updateDeviceDb(id, data);

      return result;
    } catch (error) {
      throw new ErrorHandler(error.statusCode, error.message);
    }
  }

  // Soft delete device
  static async deleteDevice(id, userId) {
    try {
      const dataExist = await getDeviceByIdDb(id);

      if (dataExist.length < 1) {
        throw new ErrorHandler(404, 'Device not found');
      }

      const result = await deleteDeviceDb(id, userId);

      return result;
    } catch (error) {
      throw new ErrorHandler(error.statusCode, error.message);
    }
  }
}

module.exports = DeviceService;
