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

async function postShare(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).populate('user')
		if (!reel) {
			return res.status(404).json({ message: 'reel not found' })
		}

		const reelUser = reel.user as unknown as IUser

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

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

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

const controllers = {
	postShare
}

export default controllers
