import { Injectable } from '@nestjs/common';
import { BaseUpdateManager } from 'src/core/modules/domain/usecase/managers/base-update.manager';
import { ItemEntity } from '../../entities/item.entity';
import { ItemModel } from '../../../data/models/item.model';
import { ItemUpdatedEvent } from '../../entities/event/item-updated.event';
import {
  EventTopics,
  columnUniques,
  validateRelations,
} from 'src/core/strings/constants/interface.constants';
import { STATUS } from 'src/core/strings/constants/base.constants';

@Injectable()
export class UpdateItemManager extends BaseUpdateManager<ItemEntity> {
  protected oldBasePrice: number;

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

  async beforeProcess(): Promise<void> {
    this.oldBasePrice = this.oldData.base_price;
    return;
  }

  async afterProcess(): Promise<void> {
    const newBasePrice = this.result.base_price;
    const itemId = this.result.id;

    await this.dataService.updateItemRatePrice(
      this.oldBasePrice,
      newBasePrice,
      itemId,
    );

    if (this.result.breakdown_bundling) {
      this.dataService.updateBreakdownBundling(itemId);
    }
    return;
  }

  get validateRelations(): validateRelations[] {
    const timeGroupId = this.data.time_group_id ?? this.data.time_group?.id;
    const relation =
      this.data.bundling_items?.length > 0
        ? 'bundling_items'
        : 'bundling_parents';

    return timeGroupId != null
      ? [
          {
            relation: relation,
            singleQuery: ['time_group_id', 'not in', [timeGroupId, null]],
            message: `Gagal Update! Time group item dan bundling item tidak sama`,
          },
        ]
      : [];
  }

  get uniqueColumns(): columnUniques[] {
    const timeGroupId = this.data.time_group_id ?? this.data.time_group?.id;
    return timeGroupId != null
      ? [
          {
            column: 'name',
            query: `((${this.tableName}.time_group_id Is Null OR ${this.tableName}.time_group_id = '${timeGroupId}'))`,
          },
        ]
      : [
          {
            column: 'name',
          },
        ];
  }

  get entityTarget(): any {
    return ItemModel;
  }

  get eventTopics(): EventTopics[] {
    return [
      {
        topic: ItemUpdatedEvent,
      },
    ];
  }
}
