import { Request, Response } from 'express'
import { RewardHash } from './models'
import services from '../../utils/services'
import { IReward } from '../rewards/models'
import constants from '../../utils/constants'

async function postRewardConsume(req: Request, res: Response) {
	try {
		const id = req.params.id

		let rewardHash = await RewardHash.findById(id).populate('reward')
		if (!rewardHash) {
			return res.status(404).json({ message: 'QR is invalid' })
		}
		if (rewardHash.isConsumed) {
			return res.status(409).json({ message: 'Reward already claimed' })
		}
		const reward = rewardHash.reward as unknown as IReward
		if (!reward) {
			return res.status(404).json({ message: 'reward not found' })
		}

		if (reward.remaining <= 0) {
			return res.status(410).json({ message: 'reward is sold out' })
		}

		if (reward.expiredAt && reward.expiredAt <= new Date()) {
			return res.status(410).json({ message: 'reward is expired' })
		}

		rewardHash.isConsumed = true
		reward.remaining--
		if (reward.remaining <= 0) {
			reward.expiredAt = new Date()
		}
		await reward.save()
		await rewardHash.save();

		// sending socket
		(async () => {
			try {
				const socketPayload = {
					reward: `${reward._id}`,
					isExpired: !!reward.expiredAt,
					remaining: reward.remaining,
				}
				for (const key in constants.sockets) {
					const sockets = constants.sockets[key]
					if (!sockets) {
						continue
					}
					for (const socket of sockets) {
						services.socketNotifyUser({
							userId: `${socket.data.user._id}`,
							event: 'reward-consumed',
							data: `${socket.data.user._id}` === `${rewardHash.user}` ? { ...socketPayload, isConsumedByYou: true } : socketPayload,
						})
					}
				}
			} catch (error) {
				console.log(error)
			}
		})()

		return res.json({ message: 'QR is valid' })
	} catch (error) {
		console.log(error)
		return res.status(500).json({ message: 'server error' })
	}
}

const controllers = {
	postRewardConsume
}

export default controllers
