const ApiError = require("../errorClass");
const config = require("../../../config-handler");

async function isAuthorExists(authorId) {
	if (!authorId) return false;
	return (
		(
			await global.database.authors
				.promiseMode()
				.get({ where: { id: authorId } })
		).length !== 0
	);
}

async function checkSyntaxArgs(req, res) {
	return !!(
		// Проверка поля type.
		["author", "muzic"].indexOf(req.json?.type) !== -1 && // Проверка поля name.
		typeof req.json.name === "string" &&
		req.json.name.length >= 2 &&
		(req.json.type === "muzic"
			? true
			: config().authors_blacklist.filter((blacklisted) => {
					return req.json.name
						.toLowerCase()
						.includes(blacklisted.toLowerCase());
			  }).length === 0) && // Дополнительные поля для muzic
		(req.json.type === "muzic"
			? !!(
					// Для `muzic`
					(
						// Проверка поля author_id.
						(await isAuthorExists(req.json.author_id)) && // Проверка поля data. (Передаётся либо ничего, либо строка с base64)
						(req.json.data === undefined
							? true
							: typeof req.json.data === "string")
					)
			  )
			: true)
	);
}

module.exports = async (req, res) => {
	if (req.json === undefined) {
		// console.log(req.headers);
		throw new ApiError("METHOD_MUST_BE_POST_JSON", {
			request_method: req.method,
			"content-type": !req.headers["content-type"]
				? null
				: req.headers["content-type"],
		});
	}
	if (!(await checkSyntaxArgs(req, res))) {
		throw new ApiError("INVALID_OR_UNSYNTAX_PARAMS", {
			request_method: req.method,
			params: {
				type: req.json?.type === undefined ? null : req.json.type,
				name: req.json?.name === undefined ? null : req.json.name,
				...(req.json?.type === "muzic"
					? {
							author_id:
								req.json?.author_id === undefined ? null : req.json?.author_id,
							data: req.json?.data === undefined ? null : req.json.data,
					  }
					: {}),
			},
		});
	}
	if (req.json.type === "author") {
		let result = await global.database.authors.promiseMode().add({
			name: req.json.name,
			time: Math.round(new Date().getTime() / 1000),
		});
		return result.dataValues.id;
	} else {
		let result = await global.database.muzic.promiseMode().add({
			name: req.json.name,
			author_id: req.json.author_id,
			data:
				req.json.data === undefined
					? undefined
					: Buffer.from(req.json.data, "base64"),
			time: Math.round(new Date().getTime() / 1000),
		});
		return result.dataValues.id;
	}
};