import { Request, Response, NextFunction } from 'express'
import { validate } from 'super-easy-validator'

function getRequests(req: Request, res: Response, next: NextFunction) {
	try {
		const rules = {
			limit: 'optional|string|natural',
			page: 'optional|string|natural',
			status: 'optional|enums:pending,accepted,rejected'
		}

		const { errors } = validate(rules, req.query)
		if (errors) {
			return res.status(400).json({ message: errors[0] })
		}

		return next()
	} catch (error) {
		console.log(error)
		return res.status(500).json({ message: 'server error' })
	}
}

function postRequest(req: Request, res: Response, next: NextFunction) {
	try {
		const rules = {
			chat: 'mongoid'
		}

		const { errors } = validate(rules, req.body)
		if (errors) {
			return res.status(400).json({ message: errors[0] })
		}

		return next()
	} catch (error) {
		console.log(error)
		return res.status(500).json({ message: 'server error' })
	}
}

function getRequest(req: Request, res: Response, next: NextFunction) {
	try {
		const rules = {
			id: 'mongoid'
		}

		const { errors } = validate(rules, req.params)
		if (errors) {
			return res.status(400).json({ message: errors[0] })
		}

		return next()
	} catch (error) {
		console.log(error)
		return res.status(500).json({ message: 'server error' })
	}
}

function patchRequest(req: Request, res: Response, next: NextFunction) {
	try {
		const rules = {
			id: 'mongoid',
			status: 'string|enums:accepted,rejected'
		}

		const { errors } = validate(rules, {...req.params, ...req.body})
		if (errors) {
			return res.status(400).json({ message: errors[0] })
		}

		return next()
	} catch (error) {
		console.log(error)
		return res.status(500).json({ message: 'server error' })
	}
}

const validations = {
	getRequests,
	getRequest,
	postRequest,
	patchRequest
}

export default validations
