import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import TelegramBot from 'node-telegram-bot-api';
import { EccmConfig } from 'src/models/eccm-config.model';
import {
  CurrentIssuesEccmReport,
  CurrentIssuesEccmReportService,
} from 'src/reports/current-issues-eccm.report.service';
import { UserMetaInfoService } from 'src/user-meta-info/user-meta-info.service';
import { TelegramBotService, cutMessage } from '../telegram-bot.service';
import { TelegramBotHandlerInterface } from '../telegram.bot-handler.interface';

@Injectable()
export class CurrentIssuesEccmBotHandlerService
  implements TelegramBotHandlerInterface
{
  private forName = /\/current_issues_eccm (.+)/;
  private forCurrentUser = /\/current_issues_eccm/;
  private service: TelegramBotService;
  private eccmConfig: EccmConfig.Config;
  private logger = new Logger(CurrentIssuesEccmBotHandlerService.name);

  constructor(
    private configService: ConfigService,
    private currentIssuesEccmReportService: CurrentIssuesEccmReportService,
    private userMetaInfoService: UserMetaInfoService,
  ) {
    this.eccmConfig = this.configService.get<EccmConfig.Config>('redmineEccm');
  }

  async init(service: TelegramBotService, bot: TelegramBot): Promise<void> {
    if (!this.service) {
      this.service = service;
    }
    bot.onText(this.forCurrentUser, async (msg) => {
      const userMetaInfo = await this.userMetaInfoService.findByTelegramId(
        msg.chat.id,
      );
      const redmineUserId = userMetaInfo.user_id;
      const report = await this.currentIssuesEccmReportService.getReport({
        userIds: [redmineUserId],
        project: this.eccmConfig.projectName,
        versions: this.eccmConfig.currentVersions,
        statuses: this.eccmConfig.currentIssuesStatuses,
        fields: CurrentIssuesEccmReport.Defaults.currentIssuesFields,
      });
      this.logger.debug(`Current issues eccm report: ${report}`);
      bot.sendMessage(msg.chat.id, cutMessage(report) || 'empty report', {
        parse_mode: 'HTML',
      });
    });
  }

  getHelpMsg(): string {
    return '/current_issues_eccm - ваши текущие задачи из проекта ECCM';
  }
}
