import { Injectable } from '@nestjs/common';
import { BaseIndexManager } from 'src/core/modules/domain/usecase/managers/base-index.manager';
import { TimeGroupEntity } from '../../entities/time-group.entity';
import { SelectQueryBuilder } from 'typeorm';
import {
  Param,
  RelationParam,
} from 'src/core/modules/domain/entities/base-filter.entity';
import * as moment from 'moment';
import { ORDER_TYPE } from 'src/core/strings/constants/base.constants';

// TODO:
// Implementasikan filter by start_time, end_timen, dan max_usage_time

@Injectable()
export class IndexPublicTimeGroupManager extends BaseIndexManager<TimeGroupEntity> {
  async prepareData(): Promise<void> {
    Object.assign(this.filterParam, {
      order_by: `${this.tableName}.start_time`,
      order_type: ORDER_TYPE.ASC,
    });
    return;
  }

  async beforeProcess(): Promise<void> {
    return;
  }

  async afterProcess(): Promise<void> {
    return;
  }

  get relations(): RelationParam {
    return {
      joinRelations: ['items'],
      selectRelations: [],
      countRelations: ['items'],
    };
  }

  get selects(): string[] {
    return [
      `${this.tableName}.id`,
      `${this.tableName}.status`,
      `${this.tableName}.name`,
      `${this.tableName}.start_time`,
      `${this.tableName}.end_time`,
      `${this.tableName}.max_usage_time`,
      `${this.tableName}.created_at`,
      `${this.tableName}.creator_name`,
      `${this.tableName}.updated_at`,
      `${this.tableName}.editor_name`,
    ];
  }

  get specificFilter(): Param[] {
    return [
      {
        cols: `${this.tableName}.name`,
        data: this.filterParam.names,
      },
    ];
  }

  setQueryFilter(
    queryBuilder: SelectQueryBuilder<TimeGroupEntity>,
  ): SelectQueryBuilder<TimeGroupEntity> {
    queryBuilder.andWhere(`items.id is not null`);

    if (!this.filterParam.date) {
      const currentTime = moment().utcOffset('+07:00').format('HH:mm:ss');

      queryBuilder.andWhere(`${this.tableName}.end_time >= :current_time`, {
        current_time: currentTime,
      });
    }

    return queryBuilder;
  }
}
