import { executeQuery } from "../lib/db";

type iPatchBodyFields = {
	type?: string;
	col: string;
	value: string | number;
};

async function patch({ table, patchBody, whereClause }: { table: string; patchBody: iPatchBodyFields[]; whereClause: string }) {
	console.log(
		`
		Core patch called:
		table=${table}
		patchBody=${patchBody.length}
		whereClause=${whereClause}
	`,
		"\npatch body:",
		patchBody,
	);
	let sqlPart = ""; // default as empty string

	patchBody.forEach((field: iPatchBodyFields, idx: number) => {
		// set the update based on the field type
		if (field.type === "varchar") {
			sqlPart = `${sqlPart} ${field.col}='${field.value}'`;
		} else if (field.type === "date") {
			sqlPart = `${sqlPart} ${field.col}='${field.value}'`;
		} else {
			sqlPart = `${sqlPart} ${field.col}=${field.value}`;
		}

		// add comma if it is not the last item in the list
		if (idx + 1 < patchBody.length) {
			sqlPart = `${sqlPart}, `;
		}
	});

	const sql = `
		UPDATE
			${table}
		SET
			${sqlPart}
		WHERE
			${whereClause}
	`;

	// console.log("sql:", sql);

	await executeQuery({ query: sql });
}

// TODO: NEEDS TO BE FINISHED
// export async function post({ table, postBody, whereClause }) {
// 	console.log(`
// 		Core POST called:
// 		table=${table}
// 		postBody=${postBody.length}
// 		whereClause=${whereClause}
// 	`);

// 	let sqlPart = ""; // default as empty string

// 	postBody.forEach((field, idx) => {
// 		// set the update based on the field type
// 		if (field.type === "varchar") {
// 			sqlPart = `${sqlPart} ${field.col}='${field.value}'`;
// 		} else if (field.type === "date") {
// 			sqlPart = `${sqlPart} ${field.col}='${field.value}'`;
// 		} else {
// 			sqlPart = `${sqlPart} ${field.col}=${field.value}`;
// 		}

// 		// add comma if it is not the last item in the list
// 		if (idx + 1 < postBody.length) {
// 			sqlPart = `${sqlPart}, `;
// 		}
// 	});

// 	const sql = `
// 		INSERT INTO
// 			${table}
// 		VALUES
// 			${sqlPart}
// 		WHERE
// 			${whereClause}
// 	`;

// 	// console.log("sql:", sql);

// 	await executeQuery({ query: sql });
// }

export default {
	patch,
};
