import dayjs from "dayjs";

function toCamelCase(str: string): string {
  return str
    .toLowerCase()
    .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
}

function convertValue(value: any): any {
  if (value instanceof Date) {
    return dayjs(value);
  } else if (value === null) {
    return null;
  } else if (typeof value === "bigint") {
    return Number(value);
  }
  return value;
}

export default function ConvertQueryResultToJSON(
  rows: Record<string, any>[],
): any[] {
  return rows.map((row) => {
    const result: any = {};

    for (const [key, value] of Object.entries(row)) {
      const parts = key.split("-");
      let current = result;

      for (let i = 0; i < parts.length; i++) {
        const part = toCamelCase(parts[i]);
        if (i === parts.length - 1) {
          current[part] = convertValue(value);
        } else {
          current[part] = current[part] || {};
          current = current[part];
        }
      }
    }

    return result;
  });
}
