import { Injectable } from '@nestjs/common';
import { BaseIndexManager } from 'src/core/modules/domain/usecase/managers/base-index.manager';
import { DataSchedulingEntity } from '../../entities/data-scheduling.entity';
import { SelectQueryBuilder } from 'typeorm';
import {
  Param,
  RelationParam,
} from 'src/core/modules/domain/entities/base-filter.entity';
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
import { decryptionTotal } from '../../../infrastructure/helpers';

@Injectable()
export class IndexDataSchedulingManager extends BaseIndexManager<DataSchedulingEntity> {
  async prepareData(): Promise<void> {
    return;
  }

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

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

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

  get selects(): string[] {
    return [
      `${this.tableName}.id`,
      `${this.tableName}.status`,
      `${this.tableName}.name`,
      `${this.tableName}.indexing_key`,
      `${this.tableName}.schedule_date_from`,
      `${this.tableName}.schedule_date_to`,
      `${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<DataSchedulingEntity>,
  ): SelectQueryBuilder<DataSchedulingEntity> {
    if (this.filterParam.schedule_date_from) {
      const dateFrom = this.filterParam.schedule_date_from;
      queryBuilder.andWhere('schedule_date_from >= :dateFrom', {
        dateFrom: dateFrom,
      });
    }

    if (this.filterParam.schedule_date_to) {
      const dateTo = this.filterParam.schedule_date_to;
      queryBuilder.andWhere('schedule_date_from <= :dateTo', {
        dateTo: dateTo,
      });
    }
    return queryBuilder;
  }

  getResult(): PaginationResponse<DataSchedulingEntity> {
    const data = this.result.data;

    return {
      ...this.result,
      data: data.map((item) => {
        const total = decryptionTotal(item.indexing_key as string);
        return { ...item, indexing_key: total };
      }),
    };
  }
}
