import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import {
  IDailyActiveStatsRepository,
} from '../../../domain/repositories/daily-active-stats.repository.interface';
import { DailyActiveStats } from '../../../domain/aggregates/daily-active-stats/daily-active-stats.aggregate';
import { DailyActiveStatsMapper } from '../mappers/daily-active-stats.mapper';

@Injectable()
export class DailyActiveStatsRepositoryImpl implements IDailyActiveStatsRepository {
  constructor(
    private readonly prisma: PrismaService,
    private readonly mapper: DailyActiveStatsMapper,
  ) {}

  async upsert(stats: DailyActiveStats): Promise<void> {
    const data = this.mapper.toPersistence(stats);
    await this.prisma.dailyActiveStats.upsert({
      where: { day: stats.day },
      create: data,
      update: data,
    });
  }

  async findByDate(day: Date): Promise<DailyActiveStats | null> {
    const record = await this.prisma.dailyActiveStats.findUnique({
      where: { day },
    });
    return record ? this.mapper.toDomain(record) : null;
  }

  async findByDateRange(startDate: Date, endDate: Date): Promise<DailyActiveStats[]> {
    const records = await this.prisma.dailyActiveStats.findMany({
      where: {
        day: {
          gte: startDate,
          lte: endDate,
        },
      },
      orderBy: { day: 'asc' },
    });
    return records.map((r) => this.mapper.toDomain(r));
  }
}
