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

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;

import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.FileAttributeEntity;
import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.FileEntity;
import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.FileEntityComponentMappingVersionEntity;
import com.iqser.red.service.persistence.management.v1.processor.service.UploadService;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.dossier.file.FileModel;

import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;

@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
public class FileEntityMapper implements BiConsumer<FileModel, FileEntity> {

    Map<String, String> fileAtributeConfigIdMap;


    @Override
    public void accept(FileModel fileModel, FileEntity fileEntity) {

        fileEntity.setErrorCause(fileModel.getFileErrorInfo().getCause());
        fileEntity.setErrorQueue(fileModel.getFileErrorInfo().getQueue());
        fileEntity.setErrorService(fileModel.getFileErrorInfo().getService());
        fileEntity.setErrorTimestamp(fileModel.getFileErrorInfo().getTimestamp());
        fileEntity.setComponentMappingVersions(buildComponentVersions(fileModel));
        fileEntity.setFileAttributes(buildFileAttributes(fileModel));
    }


    private List<FileAttributeEntity> buildFileAttributes(FileModel fileModel) {

        return fileModel.getFileAttributes().entrySet()
                .stream()
                .map(entry -> {
                    if (fileAtributeConfigIdMap.get(entry.getKey()) != null) {
                        return new FileAttributeEntity(new FileAttributeEntity.FileAttributeEntityId(fileModel.getId(), fileAtributeConfigIdMap.get(entry.getKey())),
                                                       entry.getValue());
                    } else {
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .toList();
    }


    private List<FileEntityComponentMappingVersionEntity> buildComponentVersions(FileModel fileModel) {

        return fileModel.getComponentMappingVersions().entrySet()
                .stream()
                .map(entry -> new FileEntityComponentMappingVersionEntity(entry.getKey(), entry.getValue()))
                .toList();
    }

}
