import express, {Router, Request, Response} from 'express';
import {Document} from 'mongoose';
import controller from '../controllers/Generic';
import model from '../models/Location';
import productModel from '../models/Product';

const router: Router = express.Router();

router.get('/', controller.getAll(model));
router.post('/', controller.create(model));
router.get('/:id', controller.get(model));
router.put('/:id', controller.update(model));

router.delete('/:id', (req: Request, res: Response) => {
	try {
		const id = req.params.id;
		if (!id.match(/^[0-9a-fA-F]{24}$/)) {
			res.json({error: 'This is not a vaild object id'});
			return;
		}

		productModel.find({location: id}).then((result) => {
			if (!result.length) {
				model
					.findByIdAndDelete(id)
					.then((result) => {
						if (result) {
							res.send(`Deleted ${result}`);
						} else {
							res.send(`Could not find document by this id`);
						}
					})
					.catch((err) => {
						console.log(err);
						res.status(404).send('Not found');
					});
			} else {
				res.json({error: 'Cannot delete since its used in products'});
			}
		});
	} catch (err: unknown) {
		console.log(err);
		res.status(500).json({err});
	}
});

export = router;
