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

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

		limit = +limit
		page = +page
		const skip = (page - 1) * limit

		const query: any = {}
		if (search) {
			query.$or = [
				{ name: { $regex: search, $options: 'i' } },
				{ id: { $regex: search, $options: 'i' } }
			]
		}

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

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

async function getCommunity(req: Request, res: Response) {
	await helpers.runApi(res, async () => {
		const { id } = req.params

		const community = await Community.findById(id)
		if (!community) {
			return res.status(404).json({ message: 'community not found' })
		}

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

async function patchCommunity(req: Request, res: Response) {
	await helpers.runApi(res, async () => {
		const { id } = req.params
		const { isRelief } = req.body

		const community = await Community.findById(id)
		if (!community) {
			return res.status(404).json({ message: 'community not found' })
		}

		if (isRelief !== undefined) {
			community.isRelief = isRelief
		}

		await community.save()

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

async function postEmergencyContact(req: Request, res: Response) {
	await helpers.runApi(res, async () => {
		const { id } = req.params
		const { name, phone, emoji, color } = req.body

		const community = await Community.findById(id)
		if (!community) {
			return res.status(404).json({ message: 'community not found' })
		}

		const contact: any = { name, phone, emoji, color }

		// @ts-ignore
		community.emergencyContacts ??= []
		// @ts-ignore
		community.emergencyContacts.push(contact)
		await community.save()

		return res.status(201).json({ community })
	})
}

async function deleteEmergencyContact(req: Request, res: Response) {
	await helpers.runApi(res, async () => {
		const { id, contactId } = req.params

		const community = await Community.findById(id)
		if (!community) {
			return res.status(404).json({ message: 'community not found' })
		}

		if (!community.emergencyContacts) {
			return res.status(404).json({ message: 'emergency contact not found' })
		}

		const contactIndex = community.emergencyContacts.findIndex(e => `${e._id}` === `${contactId}`)
		if (contactIndex === -1) {
			return res.status(404).json({ message: 'emergency contact not found' })
		}

		community.emergencyContacts.splice(contactIndex, 1)
		await community.save()

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

const controllers = {
	getCommunities,
	getCommunity,
	patchCommunity,
	postEmergencyContact,
	deleteEmergencyContact
}

export default controllers
