import { IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { Inject, Injectable } from '@nestjs/common';
import { GetDauStatsQuery } from './get-dau-stats.query';
import { IDailyActiveStatsRepository, DAILY_ACTIVE_STATS_REPOSITORY } from '../../../domain/repositories/daily-active-stats.repository.interface';

export interface DauStatsResult {
  data: { day: string; dauCount: number }[];
  total: number;
}

@Injectable()
@QueryHandler(GetDauStatsQuery)
export class GetDauStatsHandler implements IQueryHandler<GetDauStatsQuery> {
  constructor(
    @Inject(DAILY_ACTIVE_STATS_REPOSITORY)
    private readonly dauStatsRepository: IDailyActiveStatsRepository,
  ) {}

  async execute(query: GetDauStatsQuery): Promise<DauStatsResult> {
    const statsList = await this.dauStatsRepository.findByDateRange(query.startDate, query.endDate);
    const data = statsList.map((stats) => ({
      day: stats.day.toISOString().split('T')[0],
      dauCount: stats.dauCount,
    }));
    return { data, total: data.length };
  }
}
