import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { ReportService, ReportType } from './report.service';
import { AiSummaryService } from './ai-summary.service';
import { ExcelService } from './excel.service';
import { ReportPdfService } from './report-pdf.service';
import { MailerService } from './mailer.service';

@Injectable()
export class ReportScheduler {
  private readonly logger = new Logger(ReportScheduler.name);

  constructor(
    private readonly reportService: ReportService,
    private readonly ai: AiSummaryService,
    private readonly excel: ExcelService,
    private readonly pdf: ReportPdfService,
    private readonly mailer: MailerService,
  ) {}

  /** Full pipeline: query -> AI summary -> Excel + PDF -> email (Excel & PDF attached). */
  async runAndSend(
    year: number,
    month: number,
    senderUserId: number,
    to?: string,
    type: ReportType = 'all',
  ): Promise<{ total: number }> {
    const report = await this.reportService.buildReport(year, month, type);
    const summary = await this.ai.summarize(report);
    const [excel, pdf] = await Promise.all([
      this.excel.build(report),
      this.pdf.generate(report, summary),
    ]);
    await this.mailer.sendReport(report, summary, excel, pdf, senderUserId, to);
    return { total: report.total };
  }

  /** Automatic: 1st of each month at 08:00 (Asia/Dubai). Uses env recipient, all categories. */
  @Cron('0 8 1 * *', { name: 'monthly-report', timeZone: 'Asia/Dubai' })
  async monthly(): Promise<void> {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const senderUserId = Number(process.env.REPORT_SENDER_USER_ID ?? 1);

    this.logger.log(`Cron fired: report for ${month}/${year} (sender #${senderUserId})`);
    try {
      const { total } = await this.runAndSend(year, month, senderUserId);
      this.logger.log(`Done. ${total} certificates emailed for ${month}/${year}.`);
    } catch (err) {
      this.logger.error(`Monthly report failed: ${(err as Error).message}`);
    }
  }
}