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

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;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Setter
@Service
public class V13MissingFileSizeMigration extends Migration {

    private static final String NAME = "Add missing file sizes";
    private static final long VERSION = 13;

    @Autowired
    private FileStatusPersistenceService fileStatusPersistenceService;

    @Autowired
    private FileManagementStorageService fileManagementStorageService;


    public V13MissingFileSizeMigration() {

        super(NAME, VERSION);
    }


    @Override
    protected void migrate() {

        List<FileEntity> missingFileSizeFiles = fileStatusPersistenceService.getAllFiles()
                .stream()
                .filter(file -> file.getFileSize() == null)
                .toList();

        log.info("Number of files without fileSize: {}", missingFileSizeFiles.size());

        missingFileSizeFiles.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: {}, setting filesize to 0", file.getId(), file.getDossierId(), e.getMessage());
                    fileStatusPersistenceService.updateFileSize(file.getId(), 0);
                }
            } else {
                fileStatusPersistenceService.updateFileSize(file.getId(), 0);
            }
        });
    }

}
