package getsvc

import (
	"context"

	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/core/client"
	netmapCore "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/core/netmap"
	netmapSDK "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap"
	objectSDK "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
	oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
)

type RemoteGetPrm struct {
	Address oid.Address
	Node    netmapSDK.NodeInfo
}

type RemoteGetter struct {
	s  remoteStorageConstructor
	es epochSource
	ks keyStorage
}

func (g *RemoteGetter) Get(ctx context.Context, prm RemoteGetPrm) (*objectSDK.Object, error) {
	var nodeInfo client.NodeInfo
	if err := client.NodeInfoFromRawNetmapElement(&nodeInfo, netmapCore.Node(prm.Node)); err != nil {
		return nil, err
	}
	rs, err := g.s.Get(nodeInfo)
	if err != nil {
		return nil, err
	}
	epoch, err := g.es.Epoch()
	if err != nil {
		return nil, err
	}
	key, err := g.ks.GetKey(nil)
	if err != nil {
		return nil, err
	}
	r := RemoteRequestParams{
		Epoch:      epoch,
		TTL:        1,
		PrivateKey: key,
	}
	return rs.Get(ctx, prm.Address, r)
}

func NewRemoteGetter(cc clientConstructor, es epochSource, ks keyStorage) *RemoteGetter {
	return &RemoteGetter{
		s:  &multiclientRemoteStorageConstructor{clientConstructor: cc},
		es: es,
		ks: ks,
	}
}