import { UsersService } from '@app/event-emitter/users/users.service';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { IssueAndPersonalParsedMessageModel } from 'src/models/issue-and-personal-parsed-message.model';
import { TelegramBotService } from 'src/telegram-bot/telegram-bot.service';
import Handlebars from 'handlebars';
import { RedminePublicUrlConverter } from '@app/event-emitter/converters/redmine-public-url.converter';

@Injectable()
export class PersonalNotificationAdapterService {
  private personalMessageTemplate: HandlebarsTemplateDelegate;

  constructor(
    private telegramBotService: TelegramBotService,
    private configService: ConfigService,
    private usersService: UsersService,
    private redminePublicUrlConverter: RedminePublicUrlConverter,
  ) {
    const template = this.configService.get<string>('personalMessageTemplate');
    this.personalMessageTemplate = Handlebars.compile(template);
  }

  async send(
    issueAndMessages: IssueAndPersonalParsedMessageModel,
  ): Promise<void> {
    const promises = issueAndMessages.personalParsedMessage.recipients.map(
      async (recipient) => {
        const redmineId = recipient;
        const issueUrlHtml = this.redminePublicUrlConverter.getHtmlHref(
          issueAndMessages.issue,
        );
        const sender = await this.usersService.getUser(
          issueAndMessages.personalParsedMessage.sender,
        );
        const data = {
          data: {
            issue: issueAndMessages.issue,
            messages: issueAndMessages.personalParsedMessage,
          },
          issue_url: issueUrlHtml,
          sender_name: sender.name,
          message: issueAndMessages.personalParsedMessage.message,
        };
        const message = this.personalMessageTemplate(data);
        return await this.telegramBotService.sendMessageByRedmineId(
          redmineId,
          message,
          { parse_mode: 'HTML' },
        );
      },
    );
    await Promise.all(promises);
  }
}
