const SubSectionService = require('../services/plant_sub_section.service');
const { setResponse, setResponsePaging, checkValidate } = require('../helpers/utils');
const { insertSubSectionSchema, updateSubSectionSchema } = require('../validate/plant_sub_section.schema');

class SubSectionController {
  // Get all sub sections
  static async getAll(req, res) {
    const queryParams = req.query;

    const results = await SubSectionService.getAll(queryParams);
    const response = await setResponsePaging(queryParams, results, 'Sub section found');

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

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

    const results = await SubSectionService.getById(id);
    const response = await setResponse(results, 'Sub section found');

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

  // Create sub section
  static async create(req, res) {
    const { error, value } = await checkValidate(insertSubSectionSchema, req);

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

    value.userId = req.user.user_id;

    const results = await SubSectionService.create(value);
    const response = await setResponse(results, 'Sub section created successfully');

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

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

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

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

    value.userId = req.user.user_id;

    const results = await SubSectionService.update(id, value);
    const response = await setResponse(results, 'Sub section updated successfully');

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

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

    const results = await SubSectionService.delete(id, req.user.user_id);
    const response = await setResponse(results, 'Sub section deleted successfully');

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

module.exports = SubSectionController;