package com.iqser.red.service.persistence.management.v1.processor.migration.migrations;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
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.migration.Migration;
import com.iqser.red.service.persistence.management.v1.processor.service.FileManagementStorageService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.FileStatusPersistenceService;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.dossier.file.FileType;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Setter
@Service
public class

FileSizeMigration8 extends Migration {

    private static final String NAME = "Update file size";
    private static final long VERSION = 8;

    @Autowired
    private FileStatusPersistenceService fileStatusPersistenceService;

    @Autowired
    private FileManagementStorageService fileManagementStorageService;


    public FileSizeMigration8() {

        super(NAME, VERSION);
    }


    @Override
    protected void migrate() {

        List<FileEntity> allFiles = fileStatusPersistenceService.getAllFiles();

        log.info("Number of all files: {}", allFiles.size());

        allFiles.forEach(file -> {
            // not hard deleted
            if (file.getHardDeletedTime() == null) {
                try {
                    var originFile = fileManagementStorageService.getStoredObjectBytes(file.getDossierId(), file.getId(), FileType.ORIGIN);
                    fileStatusPersistenceService.updateFileSize(file.getId(), originFile.length);
                } catch (Exception e) {
                    log.warn("Failed to load file bytes for file: {} in dossier {}. Error message: {} ", file.getId(), file.getDossierId(), e.getMessage());
                }
            }
        });

    }

}





