import { executeQuery } from "~/lib/db";
import helper from "~/functions/helper";
import { responseMessage } from "~/lib/db";

const itemType = "itemBundle";

async function getList() {
	const itemBundles = await executeQuery({
		query: `
		SELECT
			*
		FROM
			vw_itembundles
		ORDER BY
			purchasedDate desc
	`,
	});

	const list = helper.emptyOrRows(itemBundles);

	return list;
}

async function create(bundle) {
	const result = await executeQuery({
		query: `
		INSERT INTO item_bundles (
			sourceID,
			statusID,
			purchasedDate,
			shippedDate,
			deliveredDate,
			shipping
		) VALUES (
			${bundle.sourceID},
			${bundle.statusID},
			${bundle.purchasedDate},
			${bundle.shippedDate},
			${bundle.deliveredDate},
			${bundle.shipping}
		)
	`,
	});

	return responseMessage("create", itemType, result);
}

async function update(id, bundle) {
	const result = await executeQuery({
		query: `
		UPDATE
			item_bundles
		SET
			sourceID=${bundle.sourceID},
			statusID=${bundle.statusID},
			purchasedDate=${bundle.purchasedDate},
			shippedDate=${bundle.shippedDate},
			deliveredDate=${bundle.deliveredDate},
			shipping=${bundle.shipping}
		WHERE
			itemBundleID=${bundle.itemBundleID}
		`,
	});

	return responseMessage("update", itemType, result);
}

async function remove(id) {
	const result = await executeQuery({
		query: `
		DELETE FROM item_bundles WHERE itemBundleID=${id}`,
	});

	return responseMessage("delete", itemType, result);
}

async function addItemToBundle(obj) {
	const result = await executeQuery({
		query: `
		UPDATE
			items
		SET
			itemBundleID=${obj.itemBundleID}
		WHERE
			itemID=${obj.itemID}
	`,
	});

	return responseMessage("added item to bundle", itemType, result);
}

async function patch(id, body) {
	const result = await executeQuery({
		query: `
		UPDATE
			item_bundles
		SET
			isLocked=${body.isLockedGeneral}
		WHERE
			itemBundleID=${id}
	`,
	});

	return responseMessage(
		`set itemBundleID ${id} lock flag to ${body.isLockedGeneral}`,
		itemType,
		result,
	);
}

export default {
	getList,
	create,
	update,
	patch,
	remove,
	addItemToBundle,
};
