import { Request, Response } from 'express'
import { IUser } from '../users/models'
import { Contact } from './models'

async function postContacts(req: Request, res: Response) {
	interface Payload {
		contacts: Record<string, any>[]
	}
	try {
		const { contacts } = req.body as Payload
		const user = res.locals.user as IUser

		let contact = await Contact.findOne({user:user._id})
		if(contact) {
			contact.contacts = contacts as any
			await contact.save()
			return res.json({message: 'contacts sync successfully'})
		}

		await Contact.create({
			user: user._id,
			contacts
		})

		return res.status(201).json({ message: 'contacts sync successfully' })
	} catch (error) {
		console.log(error)
		return res.status(500).json({ message: 'server error' })
	}
}

const controllers = {
	postContacts
}

export default controllers
