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

const _faSr = _sr.fa

module.exports.create = [
  [
    body('name')
      .notEmpty()
      .withMessage(_faSr.required.name)
      .bail()
      .custom((value, { req }) => {
        return DownloadCategory.findOne({ name: value }).then(category => {
          if (category) return Promise.reject(_faSr.duplicated.name)
          else return true
        })
      })
  ],
  checkValidations(validationResult),
  (req, res) => {
    const data = {
      _creator: req.user_id,
      name: req.body.name
    }

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

module.exports.getAll = [
  (req, res) => {
    DownloadCategory.find({}, (err, categories) => {
      if (err) return res500(res, err)
      return res.json(categories)
    })
  }
]

module.exports.getOne = [
  (req, res) => {
    DownloadCategory.findById(req.params?.id)
      .populate('_creator', 'first_name last_name')
      .exec((err, category) => {
        if (err) return res404(res, err)
        return res.json(category)
      })
  }
]

module.exports.update = [
  [
    body('name')
      .notEmpty()
      .withMessage(_faSr.required.name)
      .bail()
      .custom((value, { req }) => {
        return DownloadCategory.findOne({ name: value }).then(category => {
          if (category && category._id.toString() !== req.params.id) return Promise.reject(_faSr.duplicated.name)
          else return true
        })
      })
  ],
  checkValidations(validationResult),
  (req, res) => {
    const data = {
      _creator: req.user_id,
      name: req.body.name
    }
    DownloadCategory.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
      if (err) return res404(res, err)
      return res.json({ message: _faSr.response.success_save })
    })
  }
]

module.exports.delete = [
  (req, res) => {
    Download.findOne({ category: req.params.id }, (err, item) => {
      if (err) return res404(res, err)
      if (item) return res.status(403).json({ message: 'این دسته بندی دارای آیتم میباشد.' })
      else {
        DownloadCategory.findByIdAndDelete(req.params.id, (err, category) => {
          if (err) return res404(res, err)
          return res.json({ message: _faSr.response.success_remove })
        })
      }
    })
  }
]
