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

import cn.reghao.oss.console.app.model.po.StoreNode;
import cn.reghao.oss.storeapi.dto.ObjectChannel;
import cn.reghao.oss.storeapi.dto.StoreNodeDto;
import cn.reghao.oss.storeapi.dto.StoreProperties;
import org.springframework.stereotype.Service;

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

/**
 * @author reghao
 * @date 2024-03-01 09:09:12
 */
@Service
public class OssStoreService {
    private final StoreNodeService storeNodeService;
    private final UploadChannelService uploadChannelService;

    public OssStoreService(StoreNodeService storeNodeService, UploadChannelService uploadChannelService) {
        this.storeNodeService = storeNodeService;
        this.uploadChannelService = uploadChannelService;
    }

    public void registerNode(StoreNodeDto storeNodeDto) {
        storeNodeService.add(storeNodeDto);
    }

    public List<ObjectChannel> getObjectChannels(String nodeAddr) {
        StoreNode storeNode = storeNodeService.getByNodeAddr(nodeAddr);
        if (storeNode == null || !storeNode.getEnabled()) {
            return Collections.emptyList();
        }

        String domain = storeNode.getDomain();
        return uploadChannelService.getByDomain(domain).stream()
                .map(uploadChannelService::getObjectChannel)
                .collect(Collectors.toList());
    }

    public StoreProperties getStoreProperties(String nodeAddr) {
        StoreNode storeNode = storeNodeService.getByNodeAddr(nodeAddr);
        String domain = storeNode.getDomain();
        String secretKey = storeNode.getSecretKey();
        String referer = storeNode.getReferer();
        return new StoreProperties(domain, secretKey, referer);
    }
}
