import { Request, Response } from 'express'
import { User } from '../../users/models'
import helpers from '../../../utils/helpers'

const PAGE_SIZE = 100

async function postSendPushToAll(req: Request, res: Response) {
	await helpers.runApi(res, async () => {
		const { title, body } = req.body as { title: string; body: string }

		// Respond immediately; do not wait for sends
		res.json({ message: 'Started sending notifications to active users' })

		// Background: paginate active users and send to each device with fcmToken
		helpers.runInBackground(async () => {
			const query: any = {
				$and: [
					{ name: { $exists: true, $nin: [null, ''] } },
					{ username: { $exists: true, $nin: [null, ''] } },
					{
						$or: [
							{ terminated: false },
							{ terminated: { $exists: false } }
						]
					}
				]
			}

			let skip = 0
			let hasMore = true

			while (hasMore) {
				const users = await User.find(query)
					.select('auth.loggedinDevices')
					.skip(skip)
					.limit(PAGE_SIZE)
					.lean()

				if (users.length === 0) {
					hasMore = false
					break
				}

				const sendPromises: Promise<void>[] = []
				for (const user of users) {
					const devices = user.auth?.loggedinDevices ?? []
					for (const device of devices) {
						if (device.fcmToken) {
							sendPromises.push(
								helpers.sendPushNotification(device.fcmToken, title, body, { type: 'admin-broadcast' })
							)
						}
					}
				}

				await Promise.allSettled(sendPromises)
				skip += PAGE_SIZE
				if (users.length < PAGE_SIZE) {
					hasMore = false
				}
			}
		})
	})
}

const controllers = {
	postSendPushToAll
}

export default controllers
