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

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

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

async function postAlert(req: Request, res: Response, next: NextFunction) {
	await helpers.runApi(res, () => {
		const rules = {
			title: 'string|min:1|max:200',
			description: 'string|min:1|max:2000',
			buttonLabel: 'string|min:1|max:100',
			action: 'string|enums:meetme,home,reel,study,event,explore,chats',
			event: 'optional|mongoid',
			reel: 'optional|mongoid',
			link: 'optional|url',
			socketNotify: 'optional|boolean',
		}
		const { errors } = validate(rules as any, req.body)
		if (errors) {
			return res.status(400).json({ message: errors[0] })
		}
		return next()
	})
}

async function putAlertMedia(req: Request, res: Response, next: NextFunction) {
	await helpers.runApi(res, () => {
		const { errors } = validate({ socketNotify: 'optional|string|boolean' } as any, req.query)
		if (errors) {
			return res.status(400).json({ message: errors[0] })
		}
		return next()
	})
}

const validations = {
	getAlerts,
	checkAlertId,
	postAlert,
	putAlertMedia,
}

export default validations
