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

import cn.reghao.oss.console.app.service.StoreNodeService;
import cn.reghao.oss.console.app.service.UploadChannelService;
import cn.reghao.oss.storeapi.dto.ServerInfo;
import cn.reghao.oss.storeapi.iface.StoreService;
import cn.reghao.oss.console.app.model.po.StoreNode;
import cn.reghao.oss.console.app.model.po.UploadChannel;
import cn.reghao.oss.console.util.AuthKeyContext;
import org.springframework.stereotype.Service;

/**
 * @author reghao
 * @date 2024-02-23 09:22:53
 */
@Service
public class OssService {
    private final UploadChannelService uploadChannelService;
    private final StoreNodeService storeNodeService;

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

    public ServerInfo getServerInfo(int channelId) throws Exception {
        int userId = AuthKeyContext.getUser();
        UploadChannel uploadChannel = uploadChannelService.getByChannelIdAndCreateBy(channelId, userId);
        if (uploadChannel == null) {
            String errMsg = String.format("channel_id %s not exist", channelId);
            throw new Exception(errMsg);
        }

        String domain = storeNodeService.getById(uploadChannel.getNodeId()).getDomain();
        String ossUrl = String.format("https://%s", domain);
        long maxSize = uploadChannel.getMaxSize();

        StoreNode storeNode = uploadChannelService.getStoreNodeByChannelId(channelId);
        if (storeNode == null) {
            String errMsg = String.format("channel_id %s not associate with any store_node", channelId);
            throw new Exception(errMsg);
        }

        String host = storeNode.getNodeAddr();
        int port = storeNode.getRpcPort();
        RemoteService<StoreService> remoteService = new RemoteService<>();
        StoreService storeService = remoteService.getService(host, port, StoreService.class);
        String token = storeService.getUploadToken(userId, channelId);
        return new ServerInfo(ossUrl, channelId, maxSize, token);
    }
}
