import { Injectable } from '@nestjs/common';
import { ReportSnapshot } from '../aggregates/report-snapshot';
import { ReportType, ReportPeriod, SnapshotData, DataSource } from '../value-objects';

@Injectable()
export class ReportGenerationDomainService {
  generateSnapshot(params: {
    reportType: ReportType;
    reportCode: string;
    reportPeriod: ReportPeriod;
    periodKey: string;
    rows: any[];
    summary?: Record<string, any>;
    metadata?: Record<string, any>;
    dataSources: string[];
    filterParams?: Record<string, any>;
    periodStartAt: Date;
    periodEndAt: Date;
    expiresAt?: Date;
  }): ReportSnapshot {
    const snapshotData = SnapshotData.create({
      rows: params.rows,
      summary: params.summary,
      metadata: params.metadata,
    });

    const dataSource = DataSource.create(params.dataSources);

    return ReportSnapshot.create({
      reportType: params.reportType,
      reportCode: params.reportCode,
      reportPeriod: params.reportPeriod,
      periodKey: params.periodKey,
      snapshotData,
      dataSource,
      filterParams: params.filterParams,
      periodStartAt: params.periodStartAt,
      periodEndAt: params.periodEndAt,
      expiresAt: params.expiresAt,
    });
  }

  calculateGrowthRate(
    currentValue: number,
    previousValue: number,
  ): number {
    if (previousValue === 0) {
      return currentValue > 0 ? 100 : 0;
    }
    return ((currentValue - previousValue) / previousValue) * 100;
  }

  calculateRank<T>(
    items: T[],
    valueGetter: (item: T) => number,
  ): (T & { rank: number })[] {
    const sorted = [...items].sort(
      (a, b) => valueGetter(b) - valueGetter(a),
    );

    return sorted.map((item, index) => ({
      ...item,
      rank: index + 1,
    }));
  }
}
