package de.avatic.lcc.service.transformer.bulk;

import de.avatic.lcc.dto.bulk.BulkOperationDTO;
import de.avatic.lcc.dto.bulk.BulkOperationState;
import de.avatic.lcc.model.bulk.BulkOperation;
import de.avatic.lcc.repositories.error.SysErrorRepository;
import de.avatic.lcc.service.transformer.error.SysErrorTransformer;
import org.springframework.stereotype.Service;

@Service
public class BulkOperationTransformer {


    private final SysErrorRepository sysErrorRepository;
    private final SysErrorTransformer sysErrorTransformer;

    public BulkOperationTransformer(SysErrorRepository sysErrorRepository, SysErrorTransformer sysErrorTransformer) {
        this.sysErrorRepository = sysErrorRepository;
        this.sysErrorTransformer = sysErrorTransformer;
    }

    public BulkOperationDTO toBulkOperationDTO(BulkOperation entity) {

        BulkOperationDTO dto = new BulkOperationDTO();

        dto.setId(entity.getId());
        dto.setFileType(entity.getFileType());
        dto.setProcessingType(entity.getProcessingType());
        dto.setState(entity.getProcessState());
        dto.setCreatedAt(entity.getCreatedAt());

        if (entity.getProcessState() == BulkOperationState.EXCEPTION) {
            var error = sysErrorRepository.getByBulkOperationId(entity.getId());

            error.ifPresent(sysError -> dto.setError(sysErrorTransformer.toSysErrorDto(sysError)));
        }


        return dto;

    }


}
