import { Injectable } from '@nestjs/common';
import { BaseDataService } from 'src/core/modules/data/service/base-data.service';
import { ItemRateEntity } from '../../domain/entities/item-rate.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { ItemRateModel } from '../models/item-rate.model';
import { CONNECTION_NAME } from 'src/core/strings/constants/base.constants';
import { In, Repository } from 'typeorm';
import { ItemModel } from 'src/modules/item-related/item/data/models/item.model';

@Injectable()
export class ItemRateDataService extends BaseDataService<ItemRateEntity> {
  constructor(
    @InjectRepository(ItemRateModel, CONNECTION_NAME.DEFAULT)
    private repo: Repository<ItemRateModel>,
    @InjectRepository(ItemModel, CONNECTION_NAME.DEFAULT)
    private itemRepo: Repository<ItemModel>,
  ) {
    super(repo);
  }

  async itemsRateTotal(season_id: string, items: string[]): Promise<number> {
    const rates = await this.repo.find({
      where: {
        season_period_id: season_id,
        item_id: In(items),
      },
    });

    return rates.reduce((total, current) => total + Number(current.price), 0);
  }

  async updateRatesBySeasonItem(
    season_id: string,
    item_id: string,
    price: number,
  ): Promise<void> {
    this.repo.update(
      {
        season_period_id: season_id,
        item_id,
      },
      { price },
    );
  }

  async findBundlingByItem(item_id: string): Promise<ItemModel[]> {
    const bundlings = await this.itemRepo.find({
      where: {
        breakdown_bundling: true,
        bundling_items: {
          id: item_id,
        },
      },
    });

    return Promise.all(
      await bundlings.map(async (bundling) => {
        return await this.itemRepo.findOne({
          relations: ['bundling_items'],
          where: {
            id: bundling.id,
          },
        });
      }),
    );
  }
}
