const ProductCategory = require('../models/product/ProductCategory')
const Product = require('../models/product/Product')
const {body, validationResult} = require('express-validator')
const dateformat = require('dateformat')
const v_m = require('../validation_messages')

module.exports.create = [
  [
    body('fa_name')
       .notEmpty().withMessage(v_m['fa'].required.title),

    body('en_name')
       .notEmpty().withMessage(v_m['fa'].required.title)
  ],
  (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})

    const data = {
      category_details: {
        fa: {
          name: req.body.fa_name
        },
        en: {
          name: req.body.en_name
        }
      },
      created_at: dateformat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
    }

    const category = new ProductCategory(data)
    category.save(err => {
      if (err) return res.status(500).json({message: err})
      return res.json({message: v_m['fa'].response.success_save})
    })
  }
]


module.exports.getAll = [
  (req, res) => {
    ProductCategory.find({}, (err, categories) => {
      if (err) return res.status(500).json({message: err})
      return res.json(categories)
    })
  }
]


module.exports.getOne = [
  (req, res) => {
    ProductCategory.findById(req.params.id, (err, category) => {
      if (err) console.log(err)
      return res.json(category)
    })
  }
]


module.exports.update = [
  [
    body('fa_name')
       .notEmpty().withMessage(v_m['fa'].required.title),

    body('en_name')
       .notEmpty().withMessage(v_m['fa'].required.title)
  ],
  (req, res) => {
    // check validation results
    const errors = validationResult(req)
    if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})

    const data = {
      category_details: {
        fa: {
          name: req.body.fa_name
        },
        en: {
          name: req.body.en_name
        }
      },
      updated_at: dateformat(Date.now(), 'yyyy-mm-dd HH:MM:ss')
    }

    ProductCategory.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
      if (err) return res.status(404).json({message: err})
      return res.json({message: v_m['fa'].response.success_save})
    })
  }
]


module.exports.delete = [
  (req, res) => {
    Product.findOne({category: req.params.id}, (err, product) => {
      if (err) console.log(err)
      if (product) return res.status(400).json({message: 'این دسته بندی دارای محصول است.'})
      else {
        ProductCategory.findByIdAndDelete(req.params.id, (err, category) => {
          if (err) return res.status(404).json({message: err})
          return res.json({message: v_m['fa'].response.success_remove})
        })
      }
    })
  }
]
