const ApiError = require("../errorClass");
const config = require("../../../config-handler");
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 : 'create-item', no_post : false });
	}
	const checker = new apiTypes.TypeChecker();
	
	await checker.checkRequired(req.body.type, apiTypes.ItemType, 'type');
	await checker.checkRequired(req.body.name, apiTypes.NameType, 'name');
	
	if (req.body.type === 'music') {
		await checker.checkRequired(req.body.author_id, apiTypes.AuthorType, 'author_id');
		await checker.checkAdditional(req.body.data, apiTypes.Base64FileType, 'data');
	}
	
	const result = await checker.calculate();
	if (!result.success) {
		throw new ApiError("UNSYNTAX_PARAMS_OR_MISSED_REQUIRED_PARAMS", result);
	}
}

router.post('/create-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");
			}
			
			const result = await database.authors.create({
				name: req.body.name,
				time: Math.round(new Date().getTime() / 1000),
			});
			res.result(result.dataValues.id);
		} else {
			const result = await database.music.create({
				name: req.body.name,
				author_id: req.body.author_id,
				data:
					(req.body.data === undefined || req.body.data === null)
						? undefined
						: Buffer.from(req.body.data, "base64"),
				time: Math.round(new Date().getTime() / 1000),
			});
			res.result(result.dataValues.id);
		}
	}
	catch (err) {
		return next(err);
	}
});

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

module.exports = router;