/**
 * Copyright IBM Corp. 2024, 2025
 */
import { GatewaysJson } from '@apic/studio-shared';
import JSZip from 'jszip';

export class ZipProcessor {
  async extractGatewaysJson(buffer: Buffer): Promise<GatewaysJson> {
    //.logDebug('0003', 'Extracting gateways.json from ZIP');
    const zip = new JSZip();
    let gatewaysJsonContent: GatewaysJson = {} as GatewaysJson;
    try {
      const zipContent = await zip.loadAsync(buffer);
      for (const fileName in zipContent.files) {
        const entry = zipContent.files[fileName];
        if (entry && !entry.dir && fileName.includes('gateways.json')) {
          try {
            const content = await entry.async('string');
            gatewaysJsonContent = JSON.parse(content);
          } catch {
            //.logError('0013', 'parsing gateways.json', `${err}`);
          }
        }
      }
    } catch {
      //.logError('0013', 'loading ZIP', `${err}`);
    }
    return gatewaysJsonContent;
  }
}
