/* eslint-disable @typescript-eslint/no-namespace */
import { TelegramBotService } from '../telegram-bot.service';
import { TelegramBotHandlerInterface } from '../telegram.bot-handler.interface';
import TelegramBot from 'node-telegram-bot-api';
import { Injectable, Logger } from '@nestjs/common';
import { UserMetaInfoService } from 'src/user-meta-info/user-meta-info.service';
import { Subject } from 'rxjs';
import { DateTime } from 'luxon';
import { ISO_DATE_FORMAT } from 'src/consts/date-time.consts';

export namespace SetDailyEccmUserCommentBotHandler {
  export namespace Models {
    export type SetDailyEccmUserComment = {
      userId: number;
      date: string;
      comment: string;
    };
  }
}

@Injectable()
export class SetDailyEccmUserCommentBotHandlerService
  implements TelegramBotHandlerInterface
{
  private service: TelegramBotService;
  private regexp = /\/set_daily_eccm_user_comment.*/g;
  private logger = new Logger(SetDailyEccmUserCommentBotHandlerService.name);

  $messages =
    new Subject<SetDailyEccmUserCommentBotHandler.Models.SetDailyEccmUserComment>();

  constructor(private userMetaInfoService: UserMetaInfoService) {
    return;
  }

  async init(service: TelegramBotService, bot: TelegramBot): Promise<void> {
    if (!this.service) {
      this.service = service;
    }
    bot.onText(this.regexp, async (msg) => {
      const userMetaInfo = await this.userMetaInfoService.findByTelegramId(
        msg.chat.id,
      );
      if (!userMetaInfo) {
        this.logger.error(`User for telegram id = ${msg.chat.id} not found`);
      }
      const redmineUserId = userMetaInfo.user_id;
      const data = this.parseData(msg.text);
      if (data) {
        this.logger.debug(
          `Setting user comment for daily eccm ` +
            `by redmineUserId = ${redmineUserId}, ` +
            `full text - ${msg.text}, ` +
            `parsed data - ${JSON.stringify(data)}`,
        );
        this.$messages.next({
          userId: redmineUserId,
          date: data.date,
          comment: data.msg,
        });
      } else {
        this.logger.error(
          `For some reason, it was not possible to get data from an incoming message - ${msg.text}`,
        );
      }
    });
  }

  getHelpMsg(): string {
    return (
      `/set_daily_eccm_user_comment ` +
      `[date=yyyy-MM-dd] <комментарий> ` +
      `- дополнительный комментарий для дейли`
    );
  }

  private parseData(src: string): { date: string; msg: string } | null {
    let text = src;

    text = text.replace('/set_daily_eccm_user_comment', '').trim();
    if (!text) {
      return null;
    }

    const dateMatch = text.match(/^date=[\d-]+/);
    if (!dateMatch) {
      return { date: DateTime.now().toFormat(ISO_DATE_FORMAT), msg: text };
    }

    const datePart = dateMatch[0];
    let dateRaw = datePart.replace('date=', '');
    text = text.replace('date=', '').trim();
    const date = DateTime.fromFormat(dateRaw, ISO_DATE_FORMAT);
    if (!date.isValid) {
      this.logger.error(`Wrong date in message - ${src}`);
      return null;
    }
    text = text.replace(dateRaw, '').trim();
    dateRaw = date.toFormat(ISO_DATE_FORMAT);
    return { date: dateRaw, msg: text };
  }
}
