package com.spring.domain.user.service;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

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

import com.spring.domain.user.dto.ChangeUserRoleApproveRequest;
import com.spring.domain.user.dto.UserFindRequest;
import com.spring.domain.user.dto.UserManagementResponse;
import com.spring.domain.user.entity.AgentUser;
import com.spring.domain.user.error.UserNotFoundException;
import com.spring.domain.user.repository.AgentUserRepository;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class UserManagementService {
    
    private final AgentUserRepository agentUserRepository;

    @Transactional(readOnly = true)
    public List<UserManagementResponse> getUsers(UserFindRequest request) {
        return agentUserRepository.findAll().stream()
                .filter(user -> UserFindRequest.matchesCriteria(user, request))
                .map(UserManagementResponse::valueOf)
                .collect(Collectors.toList());
    }

    @Transactional
    public void changeRoleApprove(List<ChangeUserRoleApproveRequest> requests) {
        for (ChangeUserRoleApproveRequest request : requests) {
            AgentUser user = agentUserRepository.findById(UUID.fromString(request.getId()))
                .orElseThrow(UserNotFoundException::new);
            user.changeUserRole(request.getUserRole());
            user.changeApproved(request.isApproved());
        }
    }

    @Transactional
    public void deleteUser(String id) {
        AgentUser user = agentUserRepository.findById(UUID.fromString(id))
                .orElseThrow(UserNotFoundException::new);
        agentUserRepository.delete(user);
    }

}
