import { Injectable } from '@nestjs/common';
import { BaseIndexManager } from 'src/core/modules/domain/usecase/managers/base-index.manager';
import { SeasonPeriodEntity } from '../../entities/season-period.entity';
import { SelectQueryBuilder } from 'typeorm';
import {
  Param,
  RelationParam,
} from 'src/core/modules/domain/entities/base-filter.entity';
import { DAY, STATUS } from 'src/core/strings/constants/base.constants';

@Injectable()
export class CurrentSeasonPeriodManager extends BaseIndexManager<SeasonPeriodEntity> {
  async prepareData(): Promise<void> {
    this.filterParam.limit = 10;
    return;
  }

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

  async afterProcess(): Promise<void> {
    const date = new Date(this.filterParam.date);
    const day = DAY[date.getDay()];
    Object.assign(this.result, {
      data: this.result.data
        .filter((data) => {
          const days: string[] = data.days ?? [];
          if (data.priority == 2) {
            return days.includes(day);
          } else {
            return true;
          }
        })
        .sort((a, b) => a.priority - b.priority),
    });
    return;
  }

  get relations(): RelationParam {
    return {
      // relation only join (for query purpose)
      joinRelations: ['season_type'],

      // relation join and select (relasi yang ingin ditampilkan),
      selectRelations: [],

      // relation yang hanya ingin dihitung (akan return number)
      countRelations: [],
    };
  }

  get selects(): string[] {
    return [
      `${this.tableName}.id`,
      `${this.tableName}.priority`,
      `${this.tableName}.created_at`,
      `${this.tableName}.creator_name`,
      `${this.tableName}.editor_name`,
      `${this.tableName}.updated_at`,
      `${this.tableName}.status`,
      `${this.tableName}.start_date`,
      `${this.tableName}.end_date`,
      `${this.tableName}.days`,
      `${this.tableName}.holiday_name`,

      'season_type.id',
      'season_type.name',
    ];
  }

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

  setQueryFilter(
    queryBuilder: SelectQueryBuilder<SeasonPeriodEntity>,
  ): SelectQueryBuilder<SeasonPeriodEntity> {
    queryBuilder.andWhere(`${this.tableName}.start_date <= :date`, {
      date: this.filterParam.date ?? new Date().toLocaleDateString(),
    });
    queryBuilder.andWhere(`${this.tableName}.end_date >= :date`, {
      date: this.filterParam.date ?? new Date().toLocaleDateString(),
    });

    queryBuilder.andWhere(`${this.tableName}.status In (:...statuses)`, {
      statuses: [STATUS.ACTIVE],
    });

    return queryBuilder;
  }
}
