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

@Injectable()
export class ItemDataService extends BaseDataService<ItemEntity> {
  constructor(
    @InjectRepository(ItemModel, CONNECTION_NAME.DEFAULT)
    private repo: Repository<ItemModel>,

    @InjectRepository(ItemRateModel, CONNECTION_NAME.DEFAULT)
    private repoItemRate: Repository<ItemRateModel>,
    private rateService: ItemRateDataService,
  ) {
    super(repo);
  }

  async updateItemRatePrice(
    oldPrice: number,
    newPrice: number,
    itemId: string,
  ): Promise<void> {
    console.log({ oldPrice, newPrice, itemId });

    this.repoItemRate.update(
      { item_id: itemId, price: oldPrice },
      { price: newPrice },
    );
  }

  async updateBreakdownBundling(id: string): Promise<void> {
    const item_rates = await this.repoItemRate.find({
      where: {
        item_id: id,
      },
    });

    for (const rate of item_rates) {
      const { item_id, season_period_id } = rate;
      const bundling = await this.repo.findOne({
        relations: ['bundling_items'],
        where: {
          id: item_id,
        },
      });

      console.log(bundling.name);
      const ids = bundling.bundling_items.map((item) => item.id);
      const totalRates = await this.rateService.itemsRateTotal(
        season_period_id,
        ids,
      );
      this.rateService.updateRatesBySeasonItem(
        season_period_id,
        bundling.id,
        totalRates,
      );
    }
  }
}
