import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { TenantAwareRepository } from '@it0/database';
import { UsageRecord } from '../../domain/entities/usage-record.entity';

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

  async sumMonthTokens(year: number, month: number): Promise<number> {
    return this.withRepository(async (repo) => {
      const start = new Date(year, month - 1, 1);
      const end = new Date(year, month, 1);
      const result = await repo
        .createQueryBuilder('ur')
        .select('COALESCE(SUM(ur.total_tokens), 0)', 'total')
        .where('ur.recorded_at >= :start AND ur.recorded_at < :end', { start, end })
        .getRawOne();
      return Number(result?.total ?? 0);
    });
  }
}
