package rpc

import (
	"context"
	"fmt"

	"gitlink.org.cn/cloudream/common/consts/errorcode"
	clitypes "gitlink.org.cn/cloudream/jcs-pub/client/types"
	"gitlink.org.cn/cloudream/jcs-pub/common/pkgs/rpc"
	hubrpc "gitlink.org.cn/cloudream/jcs-pub/common/pkgs/rpc/hub"
)

func (svc *Service) CheckCache(context context.Context, msg *hubrpc.CheckCache) (*hubrpc.CheckCacheResp, *rpc.CodeError) {
	store, err := svc.stgPool.GetShardStore(&msg.UserSpace)
	if err != nil {
		return nil, rpc.Failed(errorcode.OperationFailed, fmt.Sprintf("get shard store of user space %v: %v", msg.UserSpace, err))
	}

	infos, err := store.ListAll()
	if err != nil {
		return nil, rpc.Failed(errorcode.OperationFailed, fmt.Sprintf("listting file in shard store: %v", err))
	}

	var fileHashes []clitypes.FileHash
	for _, info := range infos {
		fileHashes = append(fileHashes, info.Hash)
	}

	return &hubrpc.CheckCacheResp{FileHashes: fileHashes}, nil
}

func (svc *Service) CacheGC(context context.Context, msg *hubrpc.CacheGC) (*hubrpc.CacheGCResp, *rpc.CodeError) {
	store, err := svc.stgPool.GetShardStore(&msg.UserSpace)
	if err != nil {
		return nil, rpc.Failed(errorcode.OperationFailed, fmt.Sprintf("get shard store of user space %v: %v", msg.UserSpace, err))
	}

	err = store.GC(msg.Availables)
	if err != nil {
		return nil, rpc.Failed(errorcode.OperationFailed, fmt.Sprintf("purging cache: %v", err))
	}

	return &hubrpc.CacheGCResp{}, nil
}
