const UnitService = require('../services/unit.service');
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
const { insertUnitSchema, updateUnitSchema } = require('../validate/unit.schema');

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

    const results = await UnitService.getAllUnits(queryParams);
    const response = await setResponsePaging(queryParams, results, 'Unit found');

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

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

    const results = await UnitService.getUnitById(id);
    const response = await setResponse(results, 'Unit found');

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

  // Create unit
  static async create(req, res) {
    const { error, value } = await checkValidate(insertUnitSchema, req);

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

    value.created_by = req.user.user_id;

    const results = await UnitService.createUnit(value);
    const response = await setResponse(results, 'Unit created successfully');

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

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

    const { error, value } = checkValidate(updateUnitSchema, req);

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

    value.updated_by = req.user.user_id;

    const results = await UnitService.updateUnit(id, value);
    const response = await setResponse(results, 'Unit updated successfully');

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

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

    const results = await UnitService.deleteUnit(id, req.user.user_id);
    const response = await setResponse(results, 'Unit deleted successfully');

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

module.exports = UnitController;
