import express, {Request, Response, Router} from 'express';
import controller from '../controllers/Generic';
import model from '../models/Product';
import multer from 'multer';
import fs from 'fs';
import path from 'path';

const upload = multer({dest: 'uploads/products'});
const router: Router = express.Router();

router.get('/', controller.getAll(model, ['category', 'location']));
router.get('/:id', controller.get(model, ['category', 'location']));
router.delete('/:id', controller.deleteDoc(model));
router.put('/:id', controller.update(model));

router.post(
	'/',
	upload.single('image'),
	async (req: Request, res: Response) => {
		try {
			if (!req.body.category || !req.body.location || !req.body.name) {
				res.json({error: 'Category, location and name are required'});
				return;
			}
			let product;
			if (!req.file) {
				product = new model({
					...req.body,
				});
			} else {
				product = new model({
					...req.body,
					image: {
						data: fs.readFileSync(
							path.join('uploads/products/' + req.file?.filename)
						),
						contentType: 'image',
					},
				});
			}
			await product.save();
			res.status(200).send(product);
		} catch (err: unknown) {
			res.status(500).send(err);
		}
	}
);

export = router;
