package ru.soune.nocopy.service.user;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.soune.nocopy.entity.user.User;
import ru.soune.nocopy.entity.user.UserAdditionalInfo;
import ru.soune.nocopy.exception.RegistrationAdditionalInfoNullException;
import ru.soune.nocopy.repository.UserAdditionalInfoRepository;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class AdditionalInfoService {

    private final UserAdditionalInfoRepository additionalInfoRepository;

    @Transactional
    public void additionalInfo(String ip, String userAgent, User user) {
        if (ip == null || userAgent == null) {
            throw new RegistrationAdditionalInfoNullException("Ip address or user agent is null");
        }

        UserAdditionalInfo userAdditionalInfo = UserAdditionalInfo.builder()
                .ipAddress(ip)
                .userAgent(userAgent)
                .user(user)
                .build();

        additionalInfoRepository.save(userAdditionalInfo);
    }

    public UserAdditionalInfo getAdditionalInfoByUser(Long userId) {
        return additionalInfoRepository.findById(userId).orElse(null);
    }

    public List<UserAdditionalInfo> getAllAdditionalInfos() {
        return additionalInfoRepository.findAll();
    }

    public void deleteAdditionalInfo(Long userId) {
        additionalInfoRepository.deleteById(userId);
    }

    @Transactional
    public Optional<UserAdditionalInfo> updateAdditionalInfo(Long userId, String ip, String userAgent) {
        return additionalInfoRepository.findById(userId)
                .map(info -> {
                    info.setIpAddress(ip);
                    info.setUserAgent(userAgent);
                    return additionalInfoRepository.save(info);
                });
    }
}
