package com.spring.domain.user.service;

import java.util.UUID;

import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.domain.user.error.UserNotFoundException;
import com.spring.domain.user.repository.AgentUserRepository;
import com.spring.infra.security.domain.UserPrincipal;
import com.spring.infra.security.error.SecurityAuthException;
import com.spring.infra.security.error.SecurityExceptionRule;
import com.spring.infra.security.service.UserAuthenticationService;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class UserPrincipalService implements UserDetailsService, UserAuthenticationService {

    private final AgentUserRepository agentUserRepository;

    @Transactional(readOnly = true)
    @Override
    public UserPrincipal loadUserByUsername(String username) throws UsernameNotFoundException {
        return UserPrincipal.valueOf(
                agentUserRepository.findByUserId(username)
                    .orElseThrow(() -> new SecurityAuthException(SecurityExceptionRule.USER_UNAUTHORIZED))
                );
    }

    @Transactional(readOnly = true)
    @Override
    public UserPrincipal getUserDetails(String key) {
        return UserPrincipal.valueOf(
                agentUserRepository.findById(UUID.fromString(key)).orElseThrow(UserNotFoundException::new)
                );
    }
    
}
