package com.iqser.red.service.persistence.management.v1.processor.dataexchange.service;

import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.dataexchange.models.FileExchangeImportModel;
import com.iqser.red.service.persistence.management.v1.processor.dataexchange.zipreaders.FileExchangeArchiveReader;
import com.iqser.red.service.persistence.management.v1.processor.dataexchange.zipreaders.ZipEntryIterator;
import com.iqser.red.service.persistence.management.v1.processor.settings.FileManagementServiceSettings;

import io.micrometer.observation.annotation.Observed;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
public class FileExchangeArchivalService {

    public static final long SIZE_THRESHOLD = 10000000000L; // 10GB
    FileManagementServiceSettings settings;


    @SneakyThrows
    @Observed(name = "FileExchangeImportService", contextualName = "read-import-archive")
    public FileExchangeImportModel readFileExchangeArchive(byte[] archive, String userId) {

        FileExchangeArchiveReader fileExchangeArchiveReader = new FileExchangeArchiveReader(userId);
        try (ZipEntryIterator zipEntryIterator = new ZipEntryIterator(archive, settings.getCompressionThresholdRatio(), SIZE_THRESHOLD)) {
            zipEntryIterator.forEachRemaining(fileExchangeArchiveReader::handleZipEntryData);
        }
        return fileExchangeArchiveReader.buildResult();
    }

}
