import express from 'express'
import Config from '../models/config'

const config = express.Router()

config.post('/:key', async (req, res, next) => {
  const { key } = req.params
  const { value, description } = req.body
  console.log('set config', key, value, description)
  if (!value) {
    const error = Error('Parameter value is mandatory.')
    error.statusCode = 400
    next(error)
  }
  try {
    const configPair = new Config({ key, value, description })
    await configPair.save()
    res.json(configPair)
  } catch (error) {
    error.statusCode = 400
    next(error)
  }
})

config.get('/:key?', async (req, res) => {
  const { key } = req.params
  const config = key
    ? await Config.findOne({ key })
    : await Config.find().select({ key: 1, value: 1, description: 1 })
  res.json({ config })
})

config.put('/:key', async (req, res) => {
  const { key } = req.params
  const { value, description } = req.body
  if (!value) {
    const error = Error('Parameter value is mandatory.')
    error.statusCode = 400
    next(error)
  }
  const config = await Config.findOneAndUpdate({ key }, { value, description })
  if (!config) {
    const error = Error('Key not found.')
    error.statusCode = 404
    next(error)
  }
  res.json({ ...config, value, description })
})

config.delete('/:key', async (req, res, next) => {
  const { key } = req.params
  const deleted = await Config.findOneAndRemove({ key })
  if (deleted) {
    res.json({ key })
  } else {
    const error = Error('Key not found.')
    error.statusCode = 404
    next(error)
  }
})

export async function listConfigs() {
  return await Config.find()
}

export default config
