import { Request, Response, NextFunction } from 'express'
import { validate } from 'super-easy-validator'
import helpers from '../../../utils/helpers'

async function getCommunities(req: Request, res: Response, next: NextFunction) {
	await helpers.runApi(res, () => {
		const rules = {
			limit: 'optional|string|natural',
			page: 'optional|string|natural',
			search: 'optional|string'
		}
		const { errors } = validate(rules, req.query)
		if (errors) {
			return res.status(400).json({ message: errors[0] })
		}
		return next()
	})
}

async function getCommunity(req: Request, res: Response, next: NextFunction) {
	await helpers.runApi(res, () => {
		const { id } = req.params
		const { errors } = validate({ id: 'mongoid' }, { id })
		if (errors) {
			return res.status(400).json({ message: errors[0] })
		}
		return next()
	})
}

async function patchCommunity(req: Request, res: Response, next: NextFunction) {
	await helpers.runApi(res, () => {
		const { id } = req.params
		const { isRelief } = req.body
		const { errors: paramErrors } = validate({ id: 'mongoid' }, { id })
		if (paramErrors) {
			return res.status(400).json({ message: paramErrors[0] })
		}
		const { errors: bodyErrors } = validate({ isRelief: 'optional|boolean' }, { isRelief })
		if (bodyErrors) {
			return res.status(400).json({ message: bodyErrors[0] })
		}
		return next()
	})
}

async function postEmergencyContact(req: Request, res: Response, next: NextFunction) {
	await helpers.runApi(res, () => {
		const { id } = req.params
		const { name, phone, emoji, color } = req.body
		const { errors: paramErrors } = validate({ id: 'mongoid' }, { id })
		if (paramErrors) {
			return res.status(400).json({ message: paramErrors[0] })
		}
		const { errors: bodyErrors } = validate({ name: 'string|min:1', phone: 'string|min:1', emoji: 'string', color: 'string' }, { name, phone, emoji, color })
		if (bodyErrors) {
			return res.status(400).json({ message: bodyErrors[0] })
		}
		return next()
	})
}

async function deleteEmergencyContact(req: Request, res: Response, next: NextFunction) {
	await helpers.runApi(res, () => {
		const { id, contactId } = req.params
		const { errors } = validate({ id: 'mongoid', contactId: 'mongoid' }, { id, contactId })
		if (errors) {
			return res.status(400).json({ message: errors[0] })
		}
		return next()
	})
}

const validations = {
	getCommunities,
	getCommunity,
	patchCommunity,
	postEmergencyContact,
	deleteEmergencyContact
}

export default validations
