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';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class CurrentUserEnhancer implements IssueEnhancerInterface {
  name = 'current-user';

  private rules: Record<string, string>;
  private logger = new Logger(CurrentUserEnhancer.name);

  constructor(private configService: ConfigService) {
    this.rules = this.configService.get<Record<string, string>>(
      'redmineCurrentUserRules',
    );
    this.logger.debug(
      `Loaded rules for current user enhancer - ${JSON.stringify(this.rules)}`,
    );
  }

  async enhance(
    issue: RedmineTypes.Issue,
  ): Promise<RedmineTypes.Issue & Record<string, any>> {
    const res: RedmineTypes.Issue & Record<string, any> = { ...issue };

    const status = issue.status.name;

    const fieldName = this.rules[status] || this.rules['*'] || null;
    if (fieldName) {
      res.current_user = { ...res[fieldName] };
    }

    return res;
  }
}
