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

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

  constructor(private readonly prisma: PrismaService) {}

  async logOut(params: {
    pagoId?: string;
    empresaId: string;
    endpoint: string;
    requestBody: object;
    responseBody?: object;
    httpStatus?: number;
    latenciaMs?: number;
  }) {
    const { pagoId, empresaId, endpoint, requestBody, responseBody, httpStatus, latenciaMs } = params;
    const redacted = this.redactPrivateKey(requestBody);
    await this.prisma.bancard_log.create({
      data: {
        pago_id: pagoId ?? null,
        empresa_id: empresaId,
        direccion: 'OUT',
        endpoint,
        http_status: httpStatus ?? null,
        request_body: redacted as any,
        response_body: responseBody as any ?? null,
        latencia_ms: latenciaMs ?? null,
      },
    }).catch((err) => this.logger.error('Error guardando log bancard OUT', err));
  }

  async logIn(params: {
    pagoId?: string;
    empresaId: string;
    endpoint: string;
    requestBody: object;
    httpStatus?: number;
    ipOrigen?: string;
  }) {
    const { pagoId, empresaId, endpoint, requestBody, httpStatus, ipOrigen } = params;
    await this.prisma.bancard_log.create({
      data: {
        pago_id: pagoId ?? null,
        empresa_id: empresaId,
        direccion: 'IN',
        endpoint,
        http_status: httpStatus ?? null,
        request_body: requestBody as any,
        ip_origen: ipOrigen ?? null,
      },
    }).catch((err) => this.logger.error('Error guardando log bancard IN', err));
  }

  private redactPrivateKey(obj: object): object {
    const str = JSON.stringify(obj);
    const redacted = str.replace(/"private_key"\s*:\s*"[^"]+"/g, '"private_key": "***"');
    return JSON.parse(redacted);
  }
}
