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

@Injectable()
export class CreateItemManager extends BaseCreateManager<ItemEntity> {
  async beforeProcess(): Promise<void> {
    Object.assign(this.data, {
      item_type: this.data.item_type.toLowerCase(),
    });

    if (this.data.limit_type) {
      Object.assign(this.data, {
        limit_type: this.data.limit_type.toLowerCase(),
      });
    }
    return;
  }

  async afterProcess(): Promise<void> {
    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', '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 eventTopics(): EventTopics[] {
    return [
      {
        topic: ItemCreatedEvent,
        data: this.data,
      },
    ];
  }

  get entityTarget(): any {
    return ItemModel;
  }
}
