import { Request, Response } from 'express'
import { IUser } from '../users/models'
import { ISuperLike, SuperLike } from './models'
import { IReel, Reel } from '../reels/models'
import { Comment } from '../comments/models'
import services from '../../utils/services'
import { IScore } from '../scores/models'

async function postSuperLike(req: Request, res: Response) {
	try {
		const user = res.locals.user as IUser
		const reelId = req.params.reelId

		const lastDay = new Date()
		lastDay.setHours(lastDay.getHours() - 24)
		const count = await SuperLike.countDocuments({
			user: user._id,
			at: { $gt: lastDay }
		})
		if (count >= 1) {
			return res.status(403).json({ message: 'Super like can\'t be given more than once in a day' })
		}

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

		const reelUser = reel.user as unknown as IUser

		let superLike = await SuperLike.findOne({
			user: user._id,
			reel: reel._id,
		}) as ISuperLike
		if (superLike) {
			return res.status(200).json({ message: 'already super-liked' })
		}

		superLike = await SuperLike.create({ user: user._id, reel: reel._id }) as unknown as ISuperLike

		(async () => {
			try {
				const count = await SuperLike.countDocuments({ reel: reel._id })
				reel.superLikes = count
				await reel.save()
				await Comment.updateMany({ user: user._id, reel: reel._id }, { $set: { superLike: superLike._id } })
			} 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 === 'create-super-like')
				if (!action || action.completed) {
					return
				}
				action.value = 1
				action.completed = true
				await services.updateScore(score as unknown as IScore)
			} catch (error) {
				console.log(error)
			}
		})()

		if (`${reelUser._id}` !== `${user._id}`) {
			await services.notifyUser({
				title: 'Your vibe got a super like',
				description: `💖 ${user.username} super liked your vibe`,
				event: 'reel-super-liked',
				user: reelUser,
				from: user._id,
				reel: reel._id,
				superLike: superLike._id
			})
		}

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

async function deleteSuperLike(req: Request, res: Response) {
	try {
		const user = res.locals.user as IUser
		const reelId = req.params.reelId

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

		const superLike = await SuperLike.findOne({
			user: user._id,
			reel: reel._id
		}) as ISuperLike
		if (!superLike) {
			return res.status(200).json({ message: 'already un-liked' })
		}

		(async () => {
			try {
				await superLike.deleteOne()
				const count = await SuperLike.countDocuments({ reel: reel._id })
				reel.superLikes = count
				await reel.save()
				await Comment.updateMany({ user: user._id, reel: reel._id }, { $unset: { superLike: '' } })
			} catch (error) {
				console.log(error)
			}
		})()

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

const controllers = {
	postSuperLike,
	deleteSuperLike
}

export default controllers
