import { Logger } from '@nestjs/common';
import { IssuesService } from '@app/event-emitter/issues/issues.service';

export type Params = {
  query: any; // TODO: add type
  schedule: string;
};

export type Report = {
  id: string;
  name: string;
  datetime: number;
  datetimeFormatted: string;
  jobInfo: JobInfo;
  params: Params; // query?, schedule?, etc TODO
  data: any;
};

export type JobInfo = {
  jobId: string;
  dashboardId: string;
  widgetId: string;
};

export class DailyEccmV2ReportTaskHandlerService {
  private logger = new Logger(DailyEccmV2ReportTaskHandlerService.name);

  private issuesService: IssuesService | null = null;

  constructor(public params: Params, public jobInfo: JobInfo) {
    return;
  }

  setIssuesService(issuesService: IssuesService): void {
    this.issuesService = issuesService;
  }

  getIssuesService(): IssuesService | null {
    if (!this.issuesService) {
      this.logger.warn(
        'DailyEccmV2ReportTaskHandlerService is not initialized, issuesService is null',
      );
      return null;
    }
    return this.issuesService;
  }

  async createReport(): Promise<void> {
    try {
      const report = await this.prepareReportData();
      await this.saveNewReport(report);
    } catch (error) {
      this.logger.error(error);
    }
  }

  async prepareReportData(): Promise<Report> {
    const issuesService = this.getIssuesService();
    if (!issuesService) {
      throw new Error(
        'Cannot create report without issuesService, DailyEccmV2ReportTaskHandlerService is not initialized',
      );
    }
    const issues = await this.issuesService.mergedTreesAndFind(
      this.params.query,
    );
    return {} as Report;
  }

  async saveNewReport(report: Report): Promise<boolean> {
    return true;
  }

  async updatePreviousReport(report: Report): Promise<boolean> {
    return true;
  }
}
