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

const startTimeRegex = /^(0?[1-9]|1[0-2]):[0-5][0-9] (AM|PM)$/

function getStatuses(req: Request, res: Response, next: NextFunction) {
	try {
		const rules = {
			limit: 'optional|string|natural',
			page: 'optional|string|natural',
			search: 'optional|string',
			categories: 'optional|string'
		}

		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 getStatusesAndEvents(req: Request, res: Response, next: NextFunction) {
	try {
		const rules = {
			limit: 'optional|string|natural',
			search: 'required|string|min:3',
		}

		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 postStatus(req: Request, res: Response, next: NextFunction) {
	try {
		const rules = {
			categories: 'arrayof:string|arrayof:min:2|arrayof:max:20',
			schedule: 'string|enums:now,later',
			startDateType: 'string|enums:today,tomorrow,custom',
			startDate: 'dateonly',
			startTime: 'string',
			title: 'optional|string|max:60',
			locationString: 'optional|string|min:3|max:100',
			latitude: 'optional|number|min:-90|max:90',
			longitude: 'optional|number|min:-180|max:180',
		}

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

		if(!startTimeRegex.test(req.body.startTime)) {
			return res.status(400).json({message: 'startTime is invalid'})
		}

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

function patchStatus(req: Request, res: Response, next: NextFunction) {
	try {
		const rules = {
			categories: 'arrayof:string|arrayof:min:2|arrayof:max:20',
			schedule: 'optional|string|enums:now,later',
			startDateType: 'optional|string|enums:today,tomorrow,custom',
			startDate: 'optional|dateonly',
			startTime: 'optional|string',
			title: 'optional|string|max:60',
			locationString: 'optional|string|min:3|max:100',
			latitude: 'optional|number|min:-90|max:90',
			longitude: 'optional|number|min:-180|max:180',
		}

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

		if(req.body.startTime && !startTimeRegex.test(req.body.startTime)) {
			return res.status(400).json({message: 'startTime is invalid'})
		}

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

const validations = {
	getStatuses,
	getStatusesAndEvents,
	postStatus,
	patchStatus
}

export default validations
