import { joinTableFormatter, type FieldType, type QueryResult } from "../types/dynamicQueries";

export function joinTableName(name: string): string {
  let normalized = joinTableFormatter[name];
  return normalized ?? name;
}

export function flattenQueryResult(result: Array<QueryResult>): Array<{ [key: string]: FieldType }> {
  function flatten(row: QueryResult, prefix: string = ""): Array<{ [key: string]: FieldType }> {
    let results: Array<{ [key: string]: FieldType }> = [{}];

    for (const key in row) {
      const value = row[key];
      const newKey = prefix ? `${prefix}_${key}` : key;

      if (Array.isArray(value) && value.every((item) => typeof item === "object" && item !== null)) {
        const arrayResults: Array<{ [key: string]: FieldType }> = [];
        value.forEach((item) => {
          const flattenedItems = flatten(item, newKey);
          arrayResults.push(...flattenedItems);
        });

        const tempResults: Array<{ [key: string]: FieldType }> = [];
        results.forEach((res) => {
          arrayResults.forEach((arrRes) => {
            tempResults.push({ ...res, ...arrRes });
          });
        });
        results = tempResults;
      } else if (value && typeof value === "object" && !Array.isArray(value)) {
        const objResults = flatten(value as QueryResult, newKey);
        const tempResults: Array<{ [key: string]: FieldType }> = [];
        results.forEach((res) => {
          objResults.forEach((objRes) => {
            tempResults.push({ ...res, ...objRes });
          });
        });
        results = tempResults;
      } else {
        results.forEach((res) => {
          res[newKey] = String(value);
        });
      }
    }
    return results;
  }

  const flattenedResults: Array<{ [key: string]: FieldType }> = [];

  result.forEach((item) => {
    const flattenedItems = flatten(item);
    flattenedResults.push(...flattenedItems);
  });

  return flattenedResults;
}
