const {
  getAllSubSectionsDb,
  getSubSectionByIdDb,
  createSubSectionDb,
  updateSubSectionDb,
  deleteSubSectionDb
} = require('../db/plant_sub_section.db');
const { ErrorHandler } = require('../helpers/error');

class SubSectionService {
  // Get all sub sections
  static async getAll(param) {
    try {
      const results = await getAllSubSectionsDb(param);

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

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

  // Get sub section by ID
  static async getById(id) {
    try {
      const result = await getSubSectionByIdDb(id);

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

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

  // Create sub section
  static async create(data) {
    try {
      if (!data || typeof data !== 'object') data = {};

      const result = await createSubSectionDb(data);

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

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

      const dataExist = await getSubSectionByIdDb(id);

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

      const result = await updateSubSectionDb(id, data);

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

  // Soft delete sub section
  static async delete(id, userId) {
    try {
      const dataExist = await getSubSectionByIdDb(id);

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

      const result = await deleteSubSectionDb(id, userId);

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

module.exports = SubSectionService;
