import { Request, Response } from 'express'
import { IUser } from '../users/models'
import { Favorite } from './models'
import { IReel, Reel } from '../reels/models'

async function getFavorites(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 match: any = { user: user._id }

		const favorites = await Favorite.find(match)
			.sort({ createdAt: -1 })
			.skip((page - 1) * limit)
			.limit(limit)
			.populate({path: 'reel', select: {vectorIndex: 0, favorites: 0, reports: 0}})
			.populate({ path: 'user', select: { name: 1, username: 1, photo: 1 } })
		const count = await Favorite.countDocuments(match)

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

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

		const f = await Favorite.findOne({ reel: reelId, user: user._id })
		if (f) {
			return res.status(409).json({ message: 'favorite already exist' })
		}

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

		const favorite = await Favorite.create({
			user: user._id,
			reel: reel._id
		});

		(async () => {
			try {
				const count = await Favorite.countDocuments({ reel: reel._id })
				reel.favorites = count
				await reel.save()
			} catch (error) {
				console.log(error)
			}
		})()

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

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

		const favorite = await Favorite.findOne({ reel: reelId, user: user._id }).populate('reel')
		if (!favorite) {
			return res.status(404).json({ message: 'favorite not found' })
		}

		(async () => {
			try {
				const reel = favorite.reel as unknown as IReel
				await favorite.deleteOne()
				const count = await Favorite.countDocuments({ reel: reel._id })
				reel.favorites = count
				await reel.save()
			} catch (error) {
				console.log(error)
			}
		})()

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

const controllers = {
	getFavorites,
	postFavorite,
	deleteFavorite
}

export default controllers
