import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { startOfDay } from '../utils/date';
import { InspectionTaskEntity } from '../tasks/inspection-task.entity';
import { InspectionRunEntity } from '../runs/inspection-run.entity';

@Injectable()
export class DashboardService {
  constructor(
    @InjectRepository(InspectionTaskEntity)
    private readonly taskRepository: Repository<InspectionTaskEntity>,
    @InjectRepository(InspectionRunEntity)
    private readonly runRepository: Repository<InspectionRunEntity>,
  ) {}

  async getSummary() {
    const today = startOfDay();

    const [todayTaskCount, todayRunCount, todayExceptionCount, recentRuns] =
      await Promise.all([
        this.taskRepository.count(),
        this.runRepository
          .createQueryBuilder('run')
          .where('run.startedAt >= :today', { today })
          .getCount(),
        this.runRepository
          .createQueryBuilder('run')
          .where('run.startedAt >= :today', { today })
          .andWhere('run.status IN (:...statuses)', {
            statuses: ['failed', 'partial'],
          })
          .getCount(),
        this.runRepository.find({
          order: { startedAt: 'DESC' },
          take: 5,
        }),
      ]);

    return {
      todayTaskCount,
      todayRunCount,
      todayExceptionCount,
      recentRuns,
    };
  }
}
