const ApiError = require("../errorClass");

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

async function isMuzicExists(id) {
	if (!id || !Number.isInteger(id)) return false;
	let result =
		(await global.database.muzic.promiseMode().get({ where: { id } }))
			.length !== 0;
	console.log("isMuzicExists", result);
	return result;
}

async function checkSyntaxArgs(req, res) {
	return !!(
		// Проверка поля type
		["author", "muzic"].includes(req.json.type) && // Проверка поля name
		(req.json.name === undefined
			? true
			: typeof req.json.name === "string" && req.json.name.length >= 2) && // Проверка id
		(req.json.type === "author"
			? await isAuthorExists(req.json.id)
			: await isMuzicExists(req.json.id)) && // Проверка при type=muzic
		(req.json.type === "muzic"
			? // Проверка поля author_id
			  (req.json.author_id === undefined
					? true
					: 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.method !== "POST") {
		throw new ApiError("METHOD_MUST_BE_POST_JSON", {
			request_method: req.method,
		});
	}
	console.log(await checkSyntaxArgs(req, res));
	if (!(await checkSyntaxArgs(req, res))) {
		throw new ApiError("INVALID_OR_UNSYNTAX_PARAMS", {
			request_method: req.method,
			params: {
				id: req.json.id === undefined ? null : req.json.id,
				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,
							data: req.json.data,
					  }
					: {}),
			},
		});
	}

	if (req.json.type === "author") {
		await global.database.authors.promiseMode().edit(
			{
				name: req.json.name,
			},
			{
				where: {
					id: req.json.id,
				},
			},
		);
	} else {
		await global.database.muzic.promiseMode().edit(
			{
				name: req.json.name,
				author_id: req.json.author_id,
				data: !req.json.data ? undefined : Buffer.from(req.json.data, "base64"),
			},
			{
				where: {
					id: req.json.id,
				},
			},
		);
	}
	return "ok";
};