import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { TenantAwareRepository } from '@it0/database';
import { MetricSnapshot } from '../../domain/entities/metric-snapshot.entity';

@Injectable()
export class MetricSnapshotRepository extends TenantAwareRepository<MetricSnapshot> {
  constructor(dataSource: DataSource) {
    super(dataSource, MetricSnapshot);
  }

  async findByServerId(serverId: string): Promise<MetricSnapshot[]> {
    return this.withRepository((repo) =>
      repo.find({ where: { serverId } as any, order: { recordedAt: 'DESC' } as any, take: 100 }),
    );
  }

  async findRecent(serverId: string, metricType: string, since: Date): Promise<MetricSnapshot[]> {
    return this.withRepository((repo) => {
      const qb = repo.createQueryBuilder('ms');
      qb.where('ms.serverId = :serverId', { serverId });
      qb.andWhere('ms.metricType = :metricType', { metricType });
      qb.andWhere('ms.recordedAt >= :since', { since });
      qb.orderBy('ms.recordedAt', 'ASC');
      return qb.getMany();
    });
  }
}
