const ApiError = require("../errorClass");
const database = require("../../../database");
const config = require("../../../config-handler");
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 : 'edit-item', no_post : false });
	}
	const checker = new apiTypes.TypeChecker();
	
	await checker.checkRequired(req.body.type, apiTypes.ItemType, 'type');
	await checker.checkAdditional(req.body.name, apiTypes.NameType, 'name');
	
	if (req.body.type === 'music') {
		await checker.checkRequired(req.body.id, apiTypes.MusicType, 'id');
		
		await checker.checkAdditional(req.body.author_id, apiTypes.AuthorType, 'author_id');
		await checker.checkAdditional(req.body.data, apiTypes.Base64FileType, 'data');
	}
	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('/edit-item', async (req, res, next) => {
	try {
		await checkSyntaxArgs(req, res);
		
		if (req.body.type === "author") {
			if (
				config().authors_blacklist.filter((blacklisted) => {
					return req.body.name
						.toLowerCase()
						.includes(blacklisted.toLowerCase());
				}).length !== 0
			) {
				throw new ApiError("AUTHOR_BLACKLISTED");
			}
			
			await database.authors.update(
				{
					name: req.body.name,
				},
				{
					where: {
						id: req.body.id,
					},
				},
			);
		} else {
			await database.music.update(
				{
					name: req.body.name,
					author_id: req.body.author_id,
					data: !req.body.data ? (req.body.data === null ? null : undefined) : Buffer.from(req.body.data, "base64"),
				},
				{
					where: {
						id: req.body.id,
					},
				},
			);
		}
		res.result("ok");
	}
	catch (err) {
		return next(err);
	}
});

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

module.exports = router;