import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
import { SelectQueryBuilder } from 'typeorm';

export function joinRelationHelper(
  relations: string[],
  tableName: TABLE_NAME,
  queryBuilder: SelectQueryBuilder<any>,
  type?: string,
) {
  relations.forEach((relation) => {
    let alias = relation;
    let relationName = `${tableName}.${relation}`;

    if (relation.split(' ').length > 1) {
      alias = relation.split(' ').pop();
      const relationpath = relation.split(' ')[0];

      if (relationpath.split('.').length > 1) relationName = relationpath;
      else relationName = `${tableName}.${relation.split(' ')[0]}`;
    } else if (relation.split('.').length > 1) {
      alias = relation.split('.').pop();
      relationName = relation;
    }

    if (type == 'count')
      queryBuilder.loadRelationCountAndMap(relationName, relationName, alias);
    else if (type == 'select')
      queryBuilder.leftJoinAndSelect(relationName, alias);
    else queryBuilder.leftJoin(relationName, alias);
  });
}
