import { Request, Response } from 'express'
import { IUser } from '../users/models'
import { View } from './models'
import { Reel } from '../reels/models'
import { IScore } from '../scores/models'
import services from '../../utils/services'

async function postView(req: Request, res: Response) {
	try {
		const user = res.locals.user as IUser
		const reelId = req.body.reel as string

		const reel = await Reel.findById(reelId)
		if(!reel) {
			return res.status(404).json({message: 'reel not found'})
		}

		(async () => {
			try {
				await View.create({
					user: user._id,
					reel: reel._id
				})
				const count = await View.countDocuments({reel: reel._id})
				reel.views = count
				await reel.save()
			} catch (error) {
				console.log(error)
			}
		})();

		(async () => {
			try {
				const score = await services.getOrCreateTodayScore(user._id)
				if (!score) {
					return
				}
				const action = score.social.actions.find(e => e.type === 'watch-vibe-dynamic')
				if (action && !action?.completed && reel.dynamic) {
					action.value = 1
					action.completed = true
				}
				const mindfulness = score.mindfulness
				score.reelsSeen++
				const hour = new Date().getHours()
				for(const action of mindfulness.actions) {
					if(action.type === 'focus-video' && hour >= action.startAt! && reel.chips?.includes('focus')) {
						action.completed = true
						action.value = 1
						score.reelsSeen = 0
					} else if(action.type === 'mindfulness-video' && hour >= action.startAt! && reel.chips?.includes('mindfulness')) {
						action.completed = true
						action.value = 1
						score.reelsSeen = 0
					} else if(action.type === 'reflection-video' && hour >= action.startAt! && reel.chips?.includes('reflection')) {
						action.completed = true
						action.value = 1
						score.reelsSeen = 0
					}
				}
				await services.updateScore(score as unknown as IScore)
			} catch (error) {
				console.log(error)
			}
		})()

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

const controllers = {
	postView
}

export default controllers
