import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AuditLog } from '../dashboard/entities/audit-log.entity';

@Injectable()
export class AuditService {
  constructor(
    @InjectRepository(AuditLog) private repo: Repository<AuditLog>,
  ) {}

  async logs(q: any) {
    const qb = this.repo.createQueryBuilder('a');
    if (q.entidade) qb.andWhere('a.entidade = :e', { e: q.entidade });
    if (q.acao) qb.andWhere('a.acao = :a', { a: q.acao });
    if (q.usuario_id) qb.andWhere('a.usuario_id = :u', { u: q.usuario_id });
    if (q.de) qb.andWhere('a.created_at >= :de', { de: q.de });
    if (q.ate) qb.andWhere('a.created_at <= :ate', { ate: q.ate });
    return qb.orderBy('a.created_at', 'DESC').limit(q.limit || 500).getMany();
  }

  async complianceReport(q: any) {
    const qb = this.repo.createQueryBuilder('a')
      .select('a.entidade', 'entidade')
      .addSelect('a.acao', 'acao')
      .addSelect('COUNT(*)', 'total')
      .groupBy('a.entidade')
      .addGroupBy('a.acao')
      .orderBy('total', 'DESC');
    if (q.de) qb.andWhere('a.created_at >= :de', { de: q.de });
    if (q.ate) qb.andWhere('a.created_at <= :ate', { ate: q.ate });
    return qb.getRawMany();
  }
}
