import { responseMessage, failureMessage, executeQuery } from "~/lib/db";
import cache from "~/functions/cache";

const itemType = "wishlist";
const cacheKeyGetList = "getWishlist";

export async function getList(isPublic: number) {
	const cacheKeyByPublicFlag = `${cacheKeyGetList}_${isPublic}`;

	let result = null;

	let query = `
		SELECT
			wishlistID,
			url,
			description,
			isPublic
		FROM
			wishlist
	`;

	if (isPublic === 1) {
		query += ` WHERE isPublic=1`;
	}

	query += ` ORDER BY url`;

	if (cache.has(cacheKeyByPublicFlag)) {
		// use the existing cache
		result = cache.get(cacheKeyByPublicFlag);
	} else {
		result = await executeQuery({ query });

		// set a new cache
		cache.set(cacheKeyByPublicFlag, result);
	}

	if (result.error) {
		throw failureMessage("get", itemType);
	}

	return result;
}

export async function getOne(path: string, wishlistID: string) {
	const isPublic = path === "authenticated" ? 0 : 1;

	const cacheKeyByPublicFlag = `${cacheKeyGetList}_${isPublic}`;

	let result = null;

	let query = `
		SELECT
			wishlistID,
			url,
			description,
			isPublic
		FROM
			wishlist
		WHERE
			wishlistID=${wishlistID}
	`;

	if (isPublic === 1) {
		query += ` AND isPublic=1`;
	}

	result = await executeQuery({ query });

	if (result.error || result.length === 0) {
		return failureMessage("getOne", itemType);
	} else {
		return result[0];
	}
}

export async function add(body) {
	const result = await executeQuery({
		query: `
			INSERT INTO wishlist (
				url,
				description,
				isPublic
			) VALUES (
				'${body.url}',
				'${body.description}',
				${body.isPublic}
			)
		`,
	});

	if (result.error) {
		throw failureMessage("create", itemType);
	}

	// get a new cache
	cache.del(`${cacheKeyGetList}_0`);
	cache.del(`${cacheKeyGetList}_1`);

	return responseMessage("create", itemType, result);
}

export async function update(id: string, body) {
	const query = `
			UPDATE
				wishlist
			SET
				url='${body.url}',
				description='${body.description}',
				isPublic=${body.isPublic}
			WHERE
				wishlistID=${id}
		`;
	// console.log("query:", query);

	const result = await executeQuery({ query });

	if (result.error) {
		return failureMessage("update", itemType);
	} else {
		// remove the cache
		cache.del(`${cacheKeyGetList}_0`);
		cache.del(`${cacheKeyGetList}_1`);

		return responseMessage("patch", itemType, result);
	}
}

export async function remove(id: string) {
	const result = await executeQuery({
		query: `DELETE FROM wishlist WHERE wishlistID=${id}`,
	});

	if (result.error) {
		throw failureMessage("delete", itemType);
	}

	// remove the cache
	cache.del(`${cacheKeyGetList}_0`);
	cache.del(`${cacheKeyGetList}_1`);

	return responseMessage("delete", itemType, result);
}
