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 DauStatsItem {
  day: string;
  dauCount: number;
  byProvince?: Record<string, number>;
  byCity?: Record<string, number>;
}

export interface DauStatsResult {
  data: DauStatsItem[];
  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 { startDate, endDate } = query;

    const statsList = await this.dauStatsRepository.findByDateRange(startDate, endDate);

    const data: DauStatsItem[] = statsList.map((stats) => ({
      day: stats.day.toISOString().split('T')[0],
      dauCount: stats.dauCount,
      byProvince: Object.fromEntries(stats.dauByProvince),
      byCity: Object.fromEntries(stats.dauByCity),
    }));

    return {
      data,
      total: data.length,
    };
  }
}
