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

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import ru.soune.nocopy.entity.user.ModerationStatus;
import ru.soune.nocopy.entity.user.User;
import ru.soune.nocopy.entity.user.moderation.UserVerification;
import ru.soune.nocopy.repository.UserRepository;
import ru.soune.nocopy.repository.UserVerificationRepository;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UserVerificationService {

    private final UserRepository userRepository;

    private final UserVerificationRepository userVerificationRepository;

    public void initUserVerification(Long userId) {
        User user = userRepository.findById(userId).orElse(null);

        if (user == null) return;

        UserVerification userVerification = UserVerification.builder()
                .moderationStatus(ModerationStatus.VERIFICATION_IN_PROGRESS)
                .userId(user.getId())
                .createdAt(LocalDateTime.now())
                .build();

        user.setVerificationStatus(ModerationStatus.VERIFICATION_IN_PROGRESS);

        userRepository.save(user);

        userVerificationRepository.save(userVerification);
    }

    public UserVerification verifyUser(Long userId, String message, Long adminId, boolean verified) {
        User user = userRepository.findById(userId).orElse(null);

        if (user == null) return null;

        UserVerification userVerification = userVerificationRepository.findById(userId).orElse(null);

        if (userVerification == null) return null;

        ModerationStatus moderationStatus = verified ? ModerationStatus.VERIFIED: ModerationStatus.VERIFICATION_FAILED;

        userVerification.setModerationStatus(moderationStatus);

        if (message != null) userVerification.setMessage(message);

        userVerification.setAdminId(adminId);

        UserVerification save = userVerificationRepository.save(userVerification);

        user.setVerificationStatus(moderationStatus);

        userRepository.save(user);

        return save;
    }

    public List<UserVerification> verifications() {
        return userVerificationRepository.findAll();
    }
}
