/**
* Copyright Super iPaaS Integration LLC, an IBM Company 2024
*/
import JSZip from 'jszip';
import { IZipManager } from '../models/interface.js';
import { LogWrapper } from '../service/log-wrapper.js';

export class ZipManager implements IZipManager {
	private readonly zip: JSZip;
	private readonly buffer: Buffer;

	constructor(buffer: Buffer) {
		this.zip = new JSZip();
		this.buffer = buffer;
		LogWrapper.logDebug('0003', 'ZipManager instance created.');
	}

	async getEntryByName(entryName: string): Promise<string | undefined> {
		LogWrapper.logInfo('0210', entryName);

		await this.zip.loadAsync(this.buffer);
		LogWrapper.logDebug('0003', 'Buffer loaded into JSZip instance.');

		const entries = this.zip.files;
		for (const entry in entries) {
			if (entry.includes(entryName)) {
				LogWrapper.logDebug('0003', `Matching entry found: ${entry}`);

				const file = this.zip.file(entry);
				if (file) {
					LogWrapper.logInfo('0211', entryName);
					return file.async('string');
				}
			}
		}

		LogWrapper.logWarn('0004', `File not found: ${entryName}. Returning undefined`);
		return undefined;
	}
}
