import { Controller, Get, Query, Res } from '@nestjs/common';
import type { Response } from 'express';
import { AuditService } from './audit.service';

@Controller('audit')
export class AuditController {
  constructor(private readonly svc: AuditService) {}

  @Get('logs')
  logs(@Query() q: any) { return this.svc.logs(q); }

  @Get('compliance-report')
  complianceReport(@Query() q: any) { return this.svc.complianceReport(q); }

  @Get('export')
  async export(@Query() q: any, @Res() res: Response) {
    const format = q.format || 'json';
    const data = await this.svc.logs(q);
    if (format === 'csv') {
      const header = 'id,usuario_id,acao,entidade,entidade_id,created_at\n';
      const rows = data.map((r: any) => `${r.id},${r.usuario_id},${r.acao},${r.entidade},${r.entidade_id},${r.created_at}`).join('\n');
      res.setHeader('Content-Type', 'text/csv');
      res.setHeader('Content-Disposition', 'attachment; filename=audit_export.csv');
      return res.send(header + rows);
    }
    res.json(data);
  }
}
