import { Injectable } from '@nestjs/common';
import { BaseIndexManager } from 'src/core/modules/domain/usecase/managers/base-index.manager';
import { SelectQueryBuilder } from 'typeorm';
import {
  Param,
  RelationParam,
} from 'src/core/modules/domain/entities/base-filter.entity';
import { ItemRateEntity } from 'src/modules/item-related/item-rate/domain/entities/item-rate.entity';

@Injectable()
export class IndexItemRatesManager extends BaseIndexManager<ItemRateEntity> {
  async prepareData(): Promise<void> {
    this.filterParam.order_by = `season_period.id`;
    return;
  }

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

  async afterProcess(): Promise<void> {
    const period_ids = this.filterParam.season_period_ids;
    this.result.data?.map((rates) => {
      const item = rates['item'];
      const item_price =
        Number(item?.total_price ?? 0) == 0
          ? item?.total_price
          : item?.base_price;

      const bundlings = item?.bundling_items ?? [];
      const bundling_items = bundlings.map((bundling) => {
        const item_rates = bundling.item_rates?.find((rate) => {
          return period_ids?.includes(rate.season_period_id);
        });
        const rate = item_rates?.price ?? 0;
        return {
          ...bundling,
          item_rates: rate,
        };
      });

      Object.assign(item, {
        price: item.price ?? item_price,
        bundling_items,
      });
    });
    return;
  }

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

      // relation join and select (relasi yang ingin ditampilkan),
      selectRelations: [
        'season_period',
        'season_period.season_type',
        'item',
        'item.bundling_items',
        'bundling_items.item_rates',
      ],

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

  get selects(): string[] {
    return [
      `${this.tableName}.id`,
      `${this.tableName}.item_id`,
      `${this.tableName}.price`,

      'item.id',
      'item.total_price',
      'item.base_price',
      'item.breakdown_bundling',
      'bundling_items.base_price',
      'bundling_items.hpp',
      'bundling_items.id',
      'bundling_items.name',

      'item_rates',

      `season_period.id`,
      `season_period.priority`,
      `season_period.created_at`,
      `season_period.creator_name`,
      `season_period.editor_name`,
      `season_period.updated_at`,
      `season_period.status`,
      `season_period.start_date`,
      `season_period.end_date`,
      `season_period.days`,
      `season_period.holiday_name`,

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

  get specificFilter(): Param[] {
    return [];
  }

  setQueryFilter(
    queryBuilder: SelectQueryBuilder<ItemRateEntity>,
  ): SelectQueryBuilder<ItemRateEntity> {
    if (this.filterParam.item_ids) {
      queryBuilder.andWhere(`${this.tableName}.item_id In (:...itemIds)`, {
        itemIds: this.filterParam.item_ids,
      });
    }

    if (this.filterParam.season_period_ids) {
      queryBuilder.andWhere(`season_period.id In (:...seasonIdss)`, {
        seasonIdss: this.filterParam.season_period_ids,
      });
    }

    if (this.filterParam.start_date) {
      queryBuilder.andWhere(`season_period.start_date <= :inputStartDate`, {
        inputStartDate: this.filterParam.end_date,
      });

      queryBuilder.andWhere(`season_period.end_date >= :inputEndDate`, {
        inputEndDate: this.filterParam.start_date,
      });
    }

    queryBuilder.addOrderBy('season_period.priority', 'ASC');

    return queryBuilder;
  }
}
