const { body, validationResult } = require('express-validator')
const Piece = require('../models/Piece')
const { res404, res500, checkValidations } = require('../plugins/controllersHelperFunctions')
const { _sr } = require('../plugins/serverResponses')
const _faSr = _sr.fa

module.exports.add_piece = [
  [body('name').notEmpty().withMessage(_faSr.required.title)],
  checkValidations(validationResult),
  (req, res) => {
    const { name, code } = req.body

    const data = { name, code }

    const piece = new Piece(data)
    piece.save(err => {
      if (err) console.log(err)
      return res.json({ message: _faSr.response.success_save })
    })
  }
]

module.exports.update_piece = [
  [body('name').notEmpty().withMessage(_faSr.required.title)],
  checkValidations(validationResult),
  (req, res) => {
    const { name, code } = req.body

    const data = { name, code }

    Piece.findByIdAndUpdate(req.params?.id, data, (err, oldData) => {
      if (err) return res404(res, 'invalid id')
      return res.json({ message: _faSr.response.success_save })
    })
  }
]

module.exports.get_one_pieces = [
  (req, res) => {
    Piece.findById(req.params?.id, (err, data) => {
      if (err) return res404(res, 'invalid id')
      return res.json(data)
    })
  }
]

module.exports.get_all_pieces = [
  (req, res) => {
    Piece.find({}, (err, data) => {
      if (err) return res500(res, err)
      return res.json(data)
    })
  }
]

module.exports.remove_piece = [
  (req, res) => {
    Piece.findByIdAndRemove(req.params?.id, (err, data) => {
      if (err) return res404(res, 'invalid id')
      return res.json({ message: _faSr.response.success_remove })
    })
  }
]
