import { Brackets, SelectQueryBuilder } from 'typeorm';
import { WhereInQueryHelper } from './or-where-in-query.helpe';
import { BaseFilterEntity } from 'src/core/modules/domain/entities/base-filter.entity';
import { BetweenQueryHelper } from './between-query.helper';
import { TABLE_NAME } from 'src/core/strings/constants/table.constants';
import { ORDER_TYPE, STATUS } from 'src/core/strings/constants/base.constants';

export function setQueryFilterDefault(
  queryBuilder: SelectQueryBuilder<any>,
  baseFilter: BaseFilterEntity,
  tableName: TABLE_NAME,
): SelectQueryBuilder<any> {
  // filter berdasarkan id pembuat
  if (!!baseFilter.created_ids)
    new WhereInQueryHelper(
      queryBuilder,
      tableName,
      'creator_id',
      baseFilter.created_ids,
      'creator_ids',
    ).getQuery();

  // filter berdasarkan tanggal terakhir dibuat
  if (!!baseFilter.created_from && !!baseFilter.created_to)
    new BetweenQueryHelper(
      queryBuilder,
      tableName,
      'created_at',
      baseFilter.created_from,
      baseFilter.created_to,
      'created',
    ).getQuery();

  // filter berdasarkan id pengubah
  if (!!baseFilter.updated_ids)
    new WhereInQueryHelper(
      queryBuilder,
      tableName,
      'editor_id',
      baseFilter.updated_ids,
      'editor_ids',
    ).getQuery();

  // filter berdasarkan tanggal terakhir update
  if (!!baseFilter.updated_from && !!baseFilter.updated_to)
    new BetweenQueryHelper(
      queryBuilder,
      tableName,
      'updated_at',
      baseFilter.updated_from,
      baseFilter.updated_to,
      'updated',
    ).getQuery();

  return queryBuilder;
}

export function getOrderBy(
  baseFilter: BaseFilterEntity,
  queryBuilder: SelectQueryBuilder<any>,
  tableName: TABLE_NAME,
) {
  let orderBys: string[] = [`${tableName}.created_at`];
  const orderType = baseFilter.order_type ?? ORDER_TYPE.DESC;

  if (!!baseFilter.order_by) {
    orderBys =
      baseFilter.order_by.split('.').length > 1
        ? [`${baseFilter.order_by}`]
        : [`${tableName}.${baseFilter.order_by}`];

    if (
      baseFilter.order_by.split('.').length == 1 &&
      baseFilter.order_by.split('.').pop() != 'id'
    ) {
      orderBys.push(`${tableName}.created_at`);
    }
  }

  for (let i = 0; i < orderBys.length; i++) {
    if (i == 0) {
      queryBuilder.orderBy(orderBys[i], orderType);
    } else {
      queryBuilder.addOrderBy(orderBys[i], orderType);
    }
  }
}
