import { RedminePublicUrlConverter } from '@app/event-emitter/converters/redmine-public-url.converter';
import { Timestamped } from '@app/event-emitter/models/timestamped';
import { Injectable } from '@nestjs/common';
import nano from 'nano';
import { DailyEccmUserCommentsService } from './daily-eccm-user-comments.service';
import {
  DailyEccmReport,
  DailyEccmReportService,
} from './daily-eccm.report.service';

@Injectable()
export class DailyEccmWithExtraDataService {
  constructor(
    private dailyEccmReportService: DailyEccmReportService,
    private dailyEccmUserCommentsService: DailyEccmUserCommentsService,
    private redminePublicUrlConverter: RedminePublicUrlConverter,
  ) {}

  async loadReport(
    name: string,
  ): Promise<
    | (DailyEccmReport.Models.Report & nano.DocumentGetResponse & Timestamped)
    | null
  > {
    const baseReportData = await this.dailyEccmReportService.loadReport(name);
    if (!baseReportData) return null;
    const userIds = baseReportData.byUsers.map((item) => item.user.id);
    const userComments = await this.dailyEccmUserCommentsService.loadComments(
      userIds,
      name,
    );
    for (let i = 0; i < baseReportData.byUsers.length; i++) {
      const byUser = baseReportData.byUsers[i];
      if (userComments[byUser.user.id]) {
        byUser.dailyMessage =
          this.redminePublicUrlConverter.enrichTextWithIssues(
            userComments[byUser.user.id],
          );
      }
    }
    return baseReportData;
  }
}
