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

import java.util.Map;

import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.FileEntity;
import com.iqser.red.service.persistence.management.v1.processor.dataexchange.models.FileExchangeImportModel;
import com.iqser.red.service.persistence.management.v1.processor.dataexchange.models.TemplateImportInfo;
import com.iqser.red.service.persistence.management.v1.processor.service.UploadService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.FileRepository;
import com.iqser.red.service.persistence.management.v1.processor.utils.FileEntityMapper;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.dossier.file.FileModel;
import com.knecon.fforesight.databasetenantcommons.providers.utils.MagicConverter;

import io.micrometer.observation.annotation.Observed;
import jakarta.transaction.Transactional;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;

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

    ManualChangesImportService manualChangesImportService;
    FileRepository fileRepository;


    @Transactional
    @Observed(name = "FileImportPersistenceService", contextualName = "import-file-to-db")
    public synchronized String saveFileToDb(String userId,
                                            FileExchangeImportModel.FileImport file,
                                            String dossierId,
                                            TemplateImportInfo templateImportInfo) { // synchronized as this is being called in an async block. Might lock up DB otherwise.

        String fileId = createFile(dossierId, userId, file, templateImportInfo.getIdMapping());

        manualChangesImportService.importManualChanges(file.getManualChanges(), fileId, userId);

        return fileId;
    }


    private String createFile(String dossierId, String userid, FileExchangeImportModel.FileImport file, Map<String, String> fileAttributeConfigMap) {

        FileModel fileModel = file.getFileModel();

        fileModel.setId(UploadService.generateFileId(fileModel.getFilename(), dossierId));

        FileEntity fileEntity = MagicConverter.convert(fileModel, FileEntity.class, new FileEntityMapper(fileAttributeConfigMap));

        fileEntity.setAssignee(userid);
        fileEntity.setLastReviewer(userid);
        fileEntity.setLastApprover(userid);
        fileEntity.setUploader(userid);

        fileEntity.setDossierId(dossierId);

        fileRepository.save(fileEntity);

        return fileEntity.getId();
    }

}
