const ApiError = require("../errorClass");
const database = require("../../../database");
const apiTypes = require("../typeChecker");

const router = require('express').Router();

async function checkSyntaxArgs(req, res) {
	if (req.body === undefined || !req.headers['content-type'].includes('json')) {
		throw new ApiError("METHOD_MUST_BE_POST_JSON", { method : 'remove-item', no_post : false });
	}
	const checker = new apiTypes.TypeChecker();
	
	await checker.checkRequired(req.body.type, apiTypes.ItemType, 'type');
	
	if (req.body.type === 'music') {
		await checker.checkRequired(req.body.id, apiTypes.MusicType, 'id');
	}
	else if (req.body.type === 'author') {
		await checker.checkRequired(req.body.id, apiTypes.AuthorType, 'id');
	}
	
	const result = await checker.calculate();
	if (!result.success) {
		throw new ApiError("UNSYNTAX_PARAMS_OR_MISSED_REQUIRED_PARAMS", result);
	}
}

router.post('/remove-item', async (req, res, next) => {
	try {
		await checkSyntaxArgs(req, res);
		
		if (req.body.type === "author") {
			// Удаляем всю музыку этого исполнителя
			await database.music.destroy({
				where: {
					author_id: req.body.id,
				},
			});
			// Удаляем исполнителя
			await database.authors.destroy({
				where: {
					id: req.body.id,
				},
			});
		} else {
			await database.music.destroy({
				where: {
					id: req.body.id,
				},
			});
		}
		res.result("ok");
	}
	catch (err) {
		return next(err);
	}
});

router.use('/remove-item', async (req, res, next) => {
	try {
		return next(new ApiError("METHOD_MUST_BE_POST_JSON", { method : 'remove-item', no_post : true }));
	}
	catch (err) {
		return next(err);
	}
});

module.exports = router;