import { Request, Response } from 'express'
import { IUser } from '../users/models'
import { Alert } from './models'
import { AlertView } from '../alert-views/models'
import helpers from '../../utils/helpers'
import constants from '../../utils/constants'

async function getSingleAlert(req: Request, res: Response) {
	await helpers.runApi(res, async () => {
		const user = res.locals.user as IUser

		const viewedAlertIds = await AlertView.distinct('alert', { user: user._id })

		const userCoords: [number, number] | null = user.location?.coordinates ?? null

		const [alert = null] = await Alert.aggregate([
			{ $match: { _id: { $nin: viewedAlertIds } } },
			{ $sort: { createdAt: -1 } },
			{
				$lookup: {
					from: 'events',
					localField: 'event',
					foreignField: '_id',
					as: 'eventDoc',
				},
			},
			{ $addFields: { eventDoc: { $arrayElemAt: ['$eventDoc', 0] } } },
			{
				$match: {
					$or: [
						// No event or event has no location — always show
						{ eventDoc: { $exists: false } },
						{ 'eventDoc.location': { $exists: false } },
						// Event has a location — only show if user is nearby
						...(userCoords
							? [
									{
										'eventDoc.location': {
											$geoWithin: {
												$centerSphere: [
													userCoords,
													constants.locationDistance / constants.earthRadius,
												],
											},
										},
									},
							  ]
							: []),
					],
				},
			},
			{ $limit: 1 },
			{ $unset: 'eventDoc' },
		])

		return res.json({ alert })
	})
}

async function postAlertViewed(req: Request, res: Response) {
	await helpers.runApi(res, async () => {
		const user = res.locals.user as IUser
		const alertId = req.params.id

		const alert = await Alert.findById(alertId)
		if (!alert) {
			return res.status(404).json({ message: 'alert not found' })
		}

		const existing = await AlertView.findOne({ user: user._id, alert: alert._id })
		if (existing) {
			return res.status(200).json({ message: 'already viewed' })
		}

		await AlertView.create({ user: user._id, alert: alert._id })

		return res.status(201).json({ message: 'alert view created successfully' })
	})
}

const controllers = {
	getSingleAlert,
	postAlertViewed,
}

export default controllers
