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

async function getCommunities(req: Request, res: Response) {
	interface Payload {
		limit?: string | number
		page?: string | number
		search?: string
	}
	await helpers.runApi(res, async () => {
		let { limit = '10', page = '1', search = '' } = req.query as unknown as Payload
		limit = +limit
		page = +page
		const match: any = { name: RegExp(search, 'i') }

		const communities = await Community.find(match)
			.sort({ createdAt: -1 })
			.skip((page - 1) * limit)
			.limit(limit)
		const count = await Community.countDocuments(match)

		return res.json({ communities, count })
	})
}

const controllers = {
	getCommunities
}

export default controllers
