import { PoolConnection, RowDataPacket } from "mysql2/promise";

type FetchNotesProps = {
  where?: [keyof DomainNote, "=" | "<" | ">" | "<=" | ">=" | "!=", any][];
  order?: [keyof DomainNote, "asc" | "desc"][];
  limit?: number;
};
export default async function fetchNotes(
  con: PoolConnection,
  { where, order, limit }: FetchNotesProps,
) {
  let params = [];
  let whereClause = "";
  let orderClause = "";
  let limitClause = limit ? `LIMIT ${limit}` : ``;

  if (where) {
    whereClause = `WHERE ${where
      .map(([key, comparator, value]) => {
        params.push(value);
        return `DN.${key.toUpperCase()} ${comparator} ?`;
      })
      .join(" AND ")}`;
  }

  if (order) {
    orderClause = `ORDER BY ${order
      .map(([key, order]) => `DN.${key.toUpperCase()} ${order.toUpperCase()}`)
      .join(", ")}`;
  }

  const query = `
  SELECT * FROM DOMAINNOTES DN
  ${whereClause}
  ${orderClause}
  ${limitClause}
  `;

  const [result] = await con.query<RowDataPacket[]>(query, params);

  return {
    operation: true,
    data: result,
  };
}
