import { Request, Response } from 'express'
import { Misc } from './models'
import { ScheduleEvent } from '../../utils/types'
import constants from '../../utils/constants'

async function getMiscVersion(req: Request, res: Response) {
	try {
		const misc = await Misc.findById("common")
		if(!misc) {
			return res.status(404).json({message: 'miscellaneous not found'})
		}
		return res.json({ version: misc.version })
	} catch (error) {
		console.error(error)
		return res.status(500).json({ message: 'server error' })
	}
}

async function postScheduler(req: Request, res: Response) {
	interface Payload {
		id: string
		event: ScheduleEvent
		data: Record<string, any>
	}
	try {
		const {id, event, data} = req.body as Payload
		res.sendStatus(200)

		const handler = constants.scheduleHandlers[event]
		await handler?.(data)
		console.log('❇️ Schedule consumed:', id)
	} catch (error) {
		console.error(error)
	}
}

const controllers = {
	getMiscVersion,
	postScheduler
}

export default controllers
