import {Request, Response} from 'express';
import {Model} from 'mongoose';

const create = (model: Model<any>) => (req: Request, res: Response) => {
	if (!req.body.name) {
		res.json({error: 'Name is required'});
		return;
	}
	const doc = new model({
		...req.body,
	});

	return doc
		.save()
		.then((result: any) => res.status(201).send(result))
		.catch((error: any) => res.status(500).json({error}));
};

const getAll =
	(model: Model<any>, populate?: string[]) => (req: Request, res: Response) => {
		model
			.find<Document>({}, {description: 0})
			.populate(populate || [])
			.then((results) => {
				return res.status(200).send(results);
			})
			.catch((error) => {
				console.log(error);
				return res.status(500).json({error});
			});
	};

const get =
	(model: Model<any>, populate?: string[]) => (req: Request, res: Response) => {
		const id = req.params.id;

		model
			.findById<Document>(id)
			.populate(populate || [])
			.then((result) => {
				if (result) {
					return res.status(200).send(result);
				} else {
					return res.status(404).json({message: 'Not found'});
				}
			})
			.catch((error) => {
				console.log(error);
				return res.status(500).json({error});
			});
	};

const deleteDoc = (model: Model<any>) => (req: Request, res: Response) => {
	const _id = req.params.id;
	model
		.findOneAndDelete<Document>({_id})
		.then((result) => {
			if (result) {
				return res.status(200).send('Successfuly deleted');
			} else {
				return res.status(404).json({message: 'Not found'});
			}
		})
		.catch((error) => {
			console.log(error);
			return res.status(500).json({error});
		});
};

const update = (model: Model<any>) => (req: Request, res: Response) => {
	const id = req.params.id;
	const data = {...req.body};
	model
		.findByIdAndUpdate(id, data)
		.then((result) => {
			if (result) {
				return res.status(200).send(result);
			} else {
				return res.json({message: 'Not found'});
			}
		})
		.catch((error) => {
			console.log(error);
			return res.status(500).json({error});
		});
};

export default {
	create,
	getAll,
	get,
	deleteDoc,
	update,
};
