package com.spring.domain.user.service;

import java.util.UUID;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.domain.user.entity.AgentUser;
import com.spring.domain.user.entity.AgentUserToken;
import com.spring.domain.user.error.UserNotFoundException;
import com.spring.domain.user.error.UserUnAuthorized;
import com.spring.domain.user.repository.AgentUserRepository;
import com.spring.domain.user.repository.AgentUserTokenRepository;
import com.spring.infra.security.service.RefreshTokenService;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class UserRefreshTokenService implements RefreshTokenService {
    
    private final AgentUserRepository agentUserRepository;
    private final AgentUserTokenRepository agentUserTokenRepository;

    @Transactional
    @Override
    public void saveRefreshToken(String userId, String refreshToken) {
        AgentUser agentUser = agentUserRepository.findByUserId(userId).orElseThrow(UserNotFoundException::new);
        agentUserTokenRepository.findById(agentUser.getId())
            .ifPresentOrElse(
                it -> it.updateRefreshToken(refreshToken),
                () -> agentUserTokenRepository.save(
                    AgentUserToken.builder()
                        .agentUser(agentUser)
                        .refreshToken(refreshToken)
                        .build()
                )
            );
    }

    @Transactional(readOnly = true)
    @Override
    public String getRefreshToken(String key) {
        return agentUserTokenRepository.findById(UUID.fromString(key)).stream()
                .map(AgentUserToken::getRefreshToken)
                .findFirst()
                .orElseThrow(UserUnAuthorized::new);
    }

    @Transactional
    @Override
    public void deleteRefreshToken(String key) {
        agentUserTokenRepository.deleteById(UUID.fromString(key));
    }

}
