import { renderToStream } from '@react-pdf/renderer';
import { ContractPDF } from './contract-template';
import { Readable } from 'stream';
import { readFile } from 'fs/promises';
import path from 'path';
import { generateContractFromTemplate } from './pdf-template-service';

async function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Buffer> {
  const chunks: Buffer[] = [];
  return new Promise((resolve, reject) => {
    stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
    stream.on('error', (err) => reject(err));
    stream.on('end', () => resolve(Buffer.concat(chunks)));
  });
}

async function getLogoBase64(): Promise<string> {
  try {
    const logoPath = path.join(process.cwd(), 'public', 'logo.png');
    const logoBuffer = await readFile(logoPath);
    return `data:image/png;base64,${logoBuffer.toString('base64')}`;
  } catch (error) {
    console.error('Logo loading error:', error);
    return '';
  }
}

export async function generateContractPDF(booking: any, location: any, photobox: any) {
  // Use template-based generation
  return generateContractFromTemplate(booking, location, photobox);
}

export async function generateSignedContractPDF(
  booking: any,
  location: any,
  photobox: any,
  signatureData: string,
  signedBy: string,
  signedAt: Date,
  signedIp: string
) {
  // Use template-based generation with signature
  return generateContractFromTemplate(booking, location, photobox, signatureData);
}
