import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { Logger } from 'pino-nestjs';
import * as QRCode from 'qrcode';

@Injectable()
export class QrService {
  constructor(private readonly logger: Logger) {}

  async generateQrCodeDataUrl(text: string): Promise<string> {
    try {
      this.logger.log(`Generating QR Code DataURL for text length ${text.length}`);
      return await QRCode.toDataURL(text, {
        errorCorrectionLevel: 'M',
        margin: 2,
        width: 300,
      });
    } catch (error: any) {
      this.logger.error('Error generating QR code DataURL', error);
      throw new InternalServerErrorException('Failed to generate QR code.');
    }
  }

  async generateQrCodeBuffer(text: string): Promise<Buffer> {
    try {
      this.logger.log(`Generating QR Code Buffer for text length ${text.length}`);
      return await QRCode.toBuffer(text, {
        errorCorrectionLevel: 'M',
        margin: 2,
        width: 300,
      });
    } catch (error: any) {
      this.logger.error('Error generating QR code Buffer', error);
      throw new InternalServerErrorException('Failed to generate QR code.');
    }
  }
}
