import { Request, Response } from 'express'
import { IUser } from '../users/models'
import { IScore, Score } from './models'
import services from '../../utils/services'

async function getScores(req: Request, res: Response) {
	interface Payload {
		limit?: string | number
		page?: string | number
	}

	try {
		const user = res.locals.user as IUser
		let {
			limit = '10',
			page = '1'
		} = req.query as unknown as Payload
		limit = +limit
		page = +page
		const skip = (page - 1) * limit

		const query = { user: user._id }
		const scores = await Score
			.find(query, { 'mindfulness.journal': 0 })
			.sort({ createdAt: -1 })
			.skip(skip)
			.limit(limit)
		const count = await Score.countDocuments(query)

		return res.json({ scores, count })
	} catch (error) {
		console.error(error)
		return res.status(500).json({ message: 'server error' })
	}
}

async function getTodayScore(req: Request, res: Response) {
	try {
		const user = res.locals.user as IUser
		const score = await services.getOrCreateTodayScore(user._id)
		if (!score) {
			return res.status(500).json({ message: 'server error' })
		}
		if (score.mindfulness.journal) {
			score.mindfulness.journal = undefined
		}
		return res.json({ score })
	} catch (error) {
		console.error(error)
		return res.status(500).json({ message: 'server error' })
	}
}

async function postScoreJournal(req: Request, res: Response) {
	try {
		const message = req.body.message as string
		const user = res.locals.user as IUser
		const score = await services.getOrCreateTodayScore(user._id)
		if (!score) {
			return res.status(500).json({ message: 'server error' })
		}
		if (score.mindfulness.journal) {
			return res.status(409).json({ message: 'journal for today already exist' })
		}
		score.mindfulness.journal = { message, at: new Date() }
		await score.save();

		(async () => {
			try {
				const score = await services.getOrCreateTodayScore(user._id)
				if (!score) {
					return
				}
				const action = score.mindfulness.actions.find(e => e.type === 'journalism')
				if (!action || action.completed) {
					return
				}
				action.value = 1
				action.completed = true
				await services.updateScore(score as unknown as IScore)
			} catch (error) {
				console.log(error)
			}
		})()

		return res.status(201).json({ message: 'journal added successfully' })
	} catch (error) {
		console.log(error)
		return res.status(500).json({ message: 'server error' })
	}
}

const scoreControllers = {
	getScores,
	getTodayScore,
	postScoreJournal
}

export default scoreControllers
