package org.ros.chatto.service;

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

import com.spencerwi.either.Result;

import org.ros.chatto.dto.AdminUserDTO;
import org.ros.chatto.model.ChatUser;
import org.ros.chatto.repository.AdminUserRepository;
import org.ros.chatto.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class AdminService {
    private final UserRepository userRepository;
    private final AdminUserRepository adminUserRepository;

    public List<AdminUserDTO> getUsers(String principal, UserDTOSpec spec) {
        switch (spec) {
        case OTHER_USERS:
            return adminUserRepository.getOtherUsers(principal);
        case ALL_USERS:
            return adminUserRepository.getAllUsers();
        case REGULAR_USERS:
            return adminUserRepository.getRegularUsers();
        default:
            throw new UnsupportedOperationException();
        }
    }

    public Result<Void> deleteUser(String userName) {
        Optional<ChatUser> user = userRepository.findByUserName(userName);
        return Result.attempt(() -> user.get()).map((u) -> {
            userRepository.delete(u);
            return (Void) null;
        });
    }
}