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

async function postUsage(req: Request, res: Response) {
	interface Payload {
		reel?: string
		seconds: number
	}
	try {
		const { reel: reelId, seconds } = req.body as Payload
		const user = res.locals.user as IUser
		let reel: IReel | null

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

		await Usage.create({
			user: user._id,
			reel: reelId,
			seconds
		})

		;(async () => {
			try {
				const score = await services.getOrCreateTodayScore(user._id)
				if(!score) {
					return
				}
				const now = new Date()
				const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
				const result = await Usage.aggregate([
					{
						$match: {
							user: user._id,
							at: {$gte: today},
							reel: reelId ? reel!._id : {$exists: false}
						}
					},
					{ 
						$group: {
							_id: null,
							seconds: { $sum: { $toDouble: '$seconds' } }
						}
					}
				])
				const seconds = result[0]?.seconds || 0
				if(reelId) {
					score.doomScrollUsageSeconds = seconds
				} else {
					score.appUsageSeconds = seconds
				}
				await score.save()
			} catch (error) {
				console.log(error)
			}
		})()

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

const controllers = {
	postUsage
}

export default controllers
