import * as qrcode from 'qrcode';
import * as fs from 'fs';
import { InternalServerErrorException } from '@nestjs/common';
import * as path from 'path';
import { ServerConstants } from 'src/constants/server.contants';

const QR_FOLDER = 'qr';
export const generateQRCode = async (idState: number, idTown: number, idActivity: number, idPoint: number) => {
  try {
    const url = `/state/${idState}/town/${idTown}/activity/${idActivity}/travel?id=${idPoint}`;
    const qrCodeImage = await qrcode.toDataURL(url);

    // Decode base64 string
    const base64Data = qrCodeImage.replace(/^data:image\/png;base64,/, '');

    // Save image to the filesystem
    const filename = path.join(ServerConstants.ROOT_STATIC_PATH, QR_FOLDER, `${idPoint}.png`);

    fs.writeFile(filename, base64Data, 'base64', (err) => {
      if (err) {
        console.error(err);
        throw new InternalServerErrorException('Error saving QR code image');
      } else {
        console.log('QR code image saved as qrcode.png');
      }
    });
  } catch (err) {
    console.error(err);
    throw new InternalServerErrorException('Error generating QR code');
  }
};
