import { Injectable } from '@nestjs/common';
import { RelationParam } from 'src/core/modules/domain/entities/base-filter.entity';
import { PaginationResponse } from 'src/core/response/domain/ok-response.interface';
import { ItemEntity } from 'src/modules/item-related/item/domain/entities/item.entity';
import { IndexItemManager } from 'src/modules/item-related/item/domain/usecases/managers/index-item.manager';
import { SelectQueryBuilder } from 'typeorm';

@Injectable()
export class BookingItemManager extends IndexItemManager {
  get relations(): RelationParam {
    return {
      // relation only join (for query purpose)
      joinRelations: [],

      // relation join and select (relasi yang ingin ditampilkan),
      selectRelations: [
        'item_category',
        'bundling_items',
        'tenant',
        'time_group',
        'item_rates',
      ],

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

  get selects(): string[] {
    const parent = super.selects;
    return [
      ...parent,
      `${this.tableName}.image_url`,
      'item_rates.id',
      'item_rates.price',
      'item_rates.season_period_id',
    ];
  }

  getResult(): PaginationResponse<ItemEntity> {
    const result = super.getResult();
    const { data, total } = result;
    const hasRates = (this.filterParam.season_period_ids?.length ?? 0) > 0;
    const items = data.map((item) => {
      const currentRate = item.item_rates.find((rate) =>
        this.filterParam.season_period_ids?.includes(rate.season_period_id),
      );
      const { item_rates, ...rest } = item;
      const rate = currentRate?.['price'] ?? rest.base_price;
      return {
        ...rest,
        base_price: hasRates ? rate : rest.base_price,
      };
    });
    return { total, data: items };
  }

  setQueryFilter(
    queryBuilder: SelectQueryBuilder<ItemEntity>,
  ): SelectQueryBuilder<ItemEntity> {
    const query = super.setQueryFilter(queryBuilder);

    query.andWhere(`${this.tableName}.status = 'active'`);

    return query;
  }
}
