import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';

export type AiAuditResultado =
  | 'ok'
  | 'blocked_validation'
  | 'blocked_parser'
  | 'error_execution'
  | 'error_llm';

export interface AiAuditEntry {
  empresa_id: string;
  usuario_id?: string | null;
  sesion_id?: string | null;
  mensaje_id?: string | null;
  pregunta: string;
  sql_generado?: string | null;
  resultado: AiAuditResultado;
  motivo_bloqueo?: string | null;
  error_mensaje?: string | null;
  ms_ejecucion?: number | null;
  filas_devueltas?: number | null;
  tokens_usados?: number | null;
  modelo_llm?: string | null;
  ip_address?: string | null;
  user_agent?: string | null;
}

@Injectable()
export class AiAuditService {
  private readonly logger = new Logger(AiAuditService.name);

  constructor(private readonly prisma: PrismaService) {}

  async log(entry: AiAuditEntry): Promise<void> {
    try {
      await this.prisma.ai_chat_audit.create({
        data: {
          empresa_id: entry.empresa_id,
          usuario_id: entry.usuario_id ?? null,
          sesion_id: entry.sesion_id ?? null,
          mensaje_id: entry.mensaje_id ?? null,
          pregunta: entry.pregunta.substring(0, 2000),
          sql_generado: entry.sql_generado ?? null,
          resultado: entry.resultado,
          motivo_bloqueo: entry.motivo_bloqueo ?? null,
          error_mensaje: entry.error_mensaje ?? null,
          ms_ejecucion: entry.ms_ejecucion ?? null,
          filas_devueltas: entry.filas_devueltas ?? null,
          tokens_usados: entry.tokens_usados ?? null,
          modelo_llm: entry.modelo_llm ?? null,
          ip_address: entry.ip_address ?? null,
          user_agent: entry.user_agent ? entry.user_agent.substring(0, 500) : null,
        },
      });
    } catch (err) {
      this.logger.error(
        `No se pudo registrar auditoría IA: ${err instanceof Error ? err.message : 'unknown'}`,
      );
    }
  }
}
