import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import { envs } from 'src/config';

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

  constructor(private readonly config: ConfigService) {}

  sign(request: string): string {
    const keyPath = envs.qzPrivateKeyPath;
    if (!keyPath) {
      this.logger.warn('QZ_PRIVATE_KEY_PATH no configurado, retornando firma vacía');
      return '';
    }
    const resolvedPath = path.isAbsolute(keyPath) ? keyPath : path.resolve(process.cwd(), keyPath);

    const keyPem = fs.readFileSync(resolvedPath, 'utf8');
    const privateKey = crypto.createPrivateKey({ key: keyPem, format: 'pem' });
    const sign = crypto.createSign('SHA512');
    sign.update(request);
    return sign.sign(privateKey, 'base64');
  }

  getCertificate(): string {
    const certPath = envs.qzCertificatePath;
    if (!certPath) {
      this.logger.warn('QZ_CERTIFICATE_PATH no configurado');
      return '';
    }
    const resolvedPath = path.isAbsolute(certPath) ? certPath : path.resolve(process.cwd(), certPath);
    return fs.readFileSync(resolvedPath, 'utf8');
  }
}
