import * as bwipjs from 'bwip-js';
import * as fs from 'fs';
import * as path from 'path';

export async function generateBarcode(
  shipmentId: string,
  serialId : string
): Promise<Express.Multer.File> {
  // Generate PNG barcode
  const png = await bwipjs.toBuffer({
    bcid: 'code128',
    text: shipmentId,
    scale: 3,
    height: 10,
    includetext: true,
    textxalign: 'center',
    alttext:serialId,
    backgroundcolor: 'FFFFFF',
  });

  // File path
  const fileName = `${shipmentId}-barcode.png`;
  const absolutePath = path.join(process.cwd(), 'uploads', fileName);

  // Relative path to store in DB / return
  const relativePath = path.join('uploads', fileName).replace(/\//g, '\\'); // uploads\file.png

  // Ensure directory exists
  fs.mkdirSync(path.dirname(absolutePath), { recursive: true });

  // Save file
  fs.writeFileSync(absolutePath, png);

  // Multer-like file object
  const file: Express.Multer.File = {
    fieldname: 'barcode',
    originalname: fileName,
    encoding: '7bit',
    mimetype: 'image/png',
    destination: path.dirname(absolutePath),
    filename: fileName,
    path: relativePath,
    size: png.length,
    buffer: png,
    stream: fs.createReadStream(absolutePath),
  } as unknown as Express.Multer.File;

  return file;
  return file;
}
