import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { DailyEccmReportService } from './daily-eccm.report.service';
import { DateTime, Duration } from 'luxon';
import { ConfigService } from '@nestjs/config';

// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Models {
  export type Time = {
    hour: number;
    minute: number;
  };
}

@Injectable()
export class DailyEccmReportTask {
  private logger = new Logger(DailyEccmReportTask.name);
  private eccmDailyTime: Models.Time;

  constructor(
    private dailyEccmReportService: DailyEccmReportService,
    private configService: ConfigService,
  ) {
    this.eccmDailyTime = this.configService.get<Models.Time>(
      'redmineEccm.dailyTime',
    );
  }

  @Cron('25 9,10 * * 1-5')
  async generateReport(): Promise<void> {
    this.logger.log(`Generate daily eccm report by cron task started`);
    const now = DateTime.now();
    const toDate = DateTime.local(
      now.year,
      now.month,
      now.day,
      this.eccmDailyTime.hour,
      this.eccmDailyTime.minute,
    );
    let duration: Duration;
    if (now.weekday == 1) {
      duration = Duration.fromObject({ days: -3 });
    } else {
      duration = Duration.fromObject({ days: -1 });
    }
    const fromDate = toDate.plus(duration);
    const name = now.toFormat('yyyy-MM-dd');
    const params = this.dailyEccmReportService.generateParams(
      fromDate.toJSDate().toISOString(),
      toDate.toJSDate().toISOString(),
      name,
    );

    const reportData = await this.dailyEccmReportService.generateReport(params);
    const saveResult = await this.dailyEccmReportService.saveReport(
      reportData,
      true,
    );
    this.logger.log(
      `Generate daily eccm report by cron task ` +
        `finished with params = ${JSON.stringify(params)} ` +
        `and result = ${saveResult}`,
    );

    return;
  }
}
