import { IssueEnhancerInterface } from '@app/event-emitter/issue-enhancers/issue-enhancer-interface';
import { RedmineTypes } from '@app/event-emitter/models/redmine-types';
import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class CategoryMergeToTagsEnhancer implements IssueEnhancerInterface {
  name = 'category-merge-to-tags';

  private logger = new Logger(CategoryMergeToTagsEnhancer.name);

  constructor(private forProjects: string[]) {
    this.logger.debug(`Enhancer created for ${forProjects}`);
  }

  async enhance(
    issue: RedmineTypes.ExtendedIssue,
  ): Promise<RedmineTypes.ExtendedIssue> {
    if (!issue || !issue?.project?.name || this.forProjects.indexOf(issue.project.name) < 0) {
      return issue;
    }
    if (!issue.tags || !this.isArray(issue.tags)) {
      issue.tags = [];
    }
    const category = issue?.category?.name?.toLowerCase()?.replaceAll(' ', '_');
    if (category && issue.tags.indexOf(category) < 0) {
      issue.tags.push(category);
    }
    return issue;
  }

  private isArray(a: any): boolean {
    return typeof a == 'object' && typeof a.length === 'number';
  }
}
