package cn.reghao.oss.web.app.service;

import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.oss.web.account.model.po.User;
import cn.reghao.oss.web.account.service.UserContext;
import cn.reghao.oss.web.app.db.repository.StoreNodeRepository;
import cn.reghao.oss.web.app.db.repository.UserNodeRepository;
import cn.reghao.oss.web.app.model.dto.UserNodeDto;
import cn.reghao.oss.web.app.model.po.StoreNode;
import cn.reghao.oss.web.app.model.po.UserNode;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

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

/**
 * @author reghao
 * @date 2024-02-27 09:49:56
 */
@Service
public class UserNodeService {
    private final UserNodeRepository userNodeRepository;
    private final StoreNodeRepository storeNodeRepository;

    public UserNodeService(UserNodeRepository userNodeRepository, StoreNodeRepository storeNodeRepository) {
        this.userNodeRepository = userNodeRepository;
        this.storeNodeRepository = storeNodeRepository;
    }

    public Result add(UserNodeDto userNodeDto) {
        String domain = userNodeDto.getDomain();
        Integer userId = UserContext.getUser().getId();
        UserNode userNode = userNodeRepository.findByDomainAndUserId(domain, userId);
        if (userNode == null) {
            StoreNode storeNode = storeNodeRepository.findByDomain(userNodeDto.getDomain());
            if (storeNode != null) {
                userNode = new UserNode(userNodeDto, userId);
                userNodeRepository.save(userNode);
                return Result.success("node added");
            }
        }

        return Result.fail("node exist");
    }

    public void delete(Integer nodeId) {
        StoreNode storeNode = storeNodeRepository.findById(nodeId).orElse(null);
        if (storeNode != null) {
            String domain = storeNode.getDomain();
            int userId = UserContext.getUser().getId();
            UserNode userNode = userNodeRepository.findByDomainAndUserId(domain, userId);
            if (userNode != null) {
                userNodeRepository.delete(userNode);
            }
        }
    }

    public List<StoreNode> getUserStoreNodes() {
        List<UserNode> list = userNodeRepository.findAll();
        if (list.isEmpty()) {
            return Collections.emptyList();
        }

        List<String> domains = list.stream().map(UserNode::getDomain).collect(Collectors.toList());
        return storeNodeRepository.findByDomainIn(domains);
    }
}
