const DeviceService = require('../services/device.service');
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
const { insertDeviceSchema, updateDeviceSchema } = require('../validate/device.schema');

class DeviceController {
  // Get all devices
  static async getAll(req, res) {
    const queryParams = req.query;

    const results = await DeviceService.getAllDevices(queryParams);
    const response = await setResponsePaging(queryParams, results, 'Device found')

    res.status(response.statusCode).json(response);
  }

  // Get device by ID
  static async getById(req, res) {
    const { id } = req.params;

    const results = await DeviceService.getDeviceById(id);
    const response = await setResponse(results, 'Device found')

    res.status(response.statusCode).json(response);
  }

  // Create device
  static async create(req, res) {
    const { error, value } = await checkValidate(insertDeviceSchema, req)

    if (error) {
      return res.status(400).json(setResponse(error, 'Validation failed', 400));
    }

    value.userId = req.user.user_id

    const results = await DeviceService.createDevice(value);
    const response = await setResponse(results, 'Device created successfully')

    return res.status(response.statusCode).json(response);
  }

  // Update device
  static async update(req, res) {
    const { id } = req.params;

    const { error, value } = checkValidate(updateDeviceSchema, req)

    if (error) {
      return res.status(400).json(setResponse(error, 'Validation failed', 400));
    }

    value.userId = req.user.user_id

    const results = await DeviceService.updateDevice(id, value);
    const response = await setResponse(results, 'Device updated successfully')

    res.status(response.statusCode).json(response);
  }

  // Soft delete device
  static async delete(req, res) {
    const { id } = req.params;

    const results = await DeviceService.deleteDevice(id, req.user.user_id);
    const response = await setResponse(results, 'Device deleted successfully')

    res.status(response.statusCode).json(response);
  }
}

module.exports = DeviceController;
