const { body, validationResult } = require('express-validator')
const Settings = require('../models/GPS.Settings')
const { checkValidations } = require('../plugins/controllersHelperFunctions')
const titleKey = 'install_fee'
const titleKeyScore = 'install_score'

module.exports.setFee = [
  [body('amount').notEmpty().isInt().withMessage('مقدار هزینه را وارد کنید')],
  checkValidations(validationResult),
  async (req, res) => {
    const { amount } = req.body
    const fee = await Settings.findOne({ title: titleKey })
    if (fee) {
      Settings.amount = amount
      await Settings.save()
      return res.status(200).json(fee)
    }
    const newFee = await Settings.create({ title: titleKey, amount })
    res.status(201).json(newFee)
  }
]

module.exports.setScore = [
  [body('score').notEmpty().isInt().withMessage('مقدار امتیاز را وارد کنید')],
  checkValidations(validationResult),
  async (req, res) => {
    const { score } = req.body
    const record = await Settings.findOne({ title: titleKeyScore })
    if (record) {
      record.amount = score
      await record.save()
      return res.status(200).json(record)
    }
    const newScore = await Settings.create({ title: titleKeyScore, amount: score })
    res.status(201).json(newScore)
  }
]

module.exports.getFee = async (req, res) => {
  const fee = await Settings.findOne({ title: titleKey })
  res.status(200).json(fee)
}
module.exports.getScore = async (req, res) => {
  const score = await Settings.findOne({ title: titleKeyScore })
  res.status(200).json(score)
}