package ru.soune.nocopy.service.file.moderation;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import ru.soune.nocopy.entity.file.moderation.ModerationPassportFile;
import ru.soune.nocopy.repository.ModerationFileRepository;
import ru.soune.nocopy.service.file.cloud.CloudStorageService;
import ru.soune.nocopy.service.user.moderation.UserVerificationService;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ModerationFileService {

    private final ModerationFileRepository moderationFileRepository;

    private final UserVerificationService userVerificationService;

    private final CloudStorageService cloudStorageService;

    public void addFiles(Long userId, Map<Integer, String> files) {
        List<ModerationPassportFile> moderationFileRepositoryByStatus =
                moderationFileRepository.findByStatus(ModerationFileStatus.ACTIVE.getName());

        if (!moderationFileRepositoryByStatus.isEmpty()) {
            disActiveDocuments(moderationFileRepositoryByStatus);
        }

        for (Map.Entry<Integer, String> file : files.entrySet()) {
            ModerationPassportFile moderationFile = ModerationPassportFile.builder().userId(userId)
                    .path(file.getValue())
                    .part(file.getKey())
                    .userId(userId)
                    .status(ModerationFileStatus.ACTIVE.getName())
                    .build();


            moderationFileRepository.save(moderationFile);
        }

        userVerificationService.initUserVerification(userId);
    }

    public List<ModerationPassportFile> getActiveFiles() {
        return moderationFileRepository.findByStatus(ModerationFileStatus.ACTIVE.getName());
    }

    public List<ModerationPassportFile> getActiveFilesByUserId(Long userId) {
        return moderationFileRepository.findByUserIdAndStatus(userId, ModerationFileStatus.ACTIVE.getName());
    }

    private void disActiveDocuments(List<ModerationPassportFile> moderationFileRepositoryByStatus) {
        for (ModerationPassportFile moderationFile : moderationFileRepositoryByStatus) {
            moderationFile.setStatus(ModerationFileStatus.NOT_ACTIVE.getName());

            moderationFileRepository.save(moderationFile);
        }
    }
}
