import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { IOnlineSnapshotRepository } from '../../../domain/repositories/online-snapshot.repository.interface';
import { OnlineSnapshot } from '../../../domain/entities/online-snapshot.entity';
import { OnlineSnapshotMapper } from '../mappers/online-snapshot.mapper';

@Injectable()
export class OnlineSnapshotRepositoryImpl implements IOnlineSnapshotRepository {
  constructor(
    private readonly prisma: PrismaService,
    private readonly mapper: OnlineSnapshotMapper,
  ) {}

  async insert(snapshot: OnlineSnapshot): Promise<OnlineSnapshot> {
    const data = this.mapper.toPersistence(snapshot);
    const created = await this.prisma.onlineSnapshot.create({ data });
    return this.mapper.toDomain(created);
  }

  async findByTimeRange(startTime: Date, endTime: Date, interval?: string): Promise<OnlineSnapshot[]> {
    const records = await this.prisma.onlineSnapshot.findMany({
      where: { ts: { gte: startTime, lte: endTime } },
      orderBy: { ts: 'asc' },
    });
    return records.map((r) => this.mapper.toDomain(r));
  }

  async findLatest(): Promise<OnlineSnapshot | null> {
    const record = await this.prisma.onlineSnapshot.findFirst({ orderBy: { ts: 'desc' } });
    return record ? this.mapper.toDomain(record) : null;
  }
}
