package deletesvc

import (
	"context"

	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/core/netmap"
	getsvc "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/services/object/get"
	putsvc "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/services/object/put"
	searchsvc "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/services/object/search"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/services/object/util"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/util/logger"
	objectSDK "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
	oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
	"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/user"
	"go.uber.org/zap"
)

// Service utility serving requests of Object.Get service.
type Service struct {
	*cfg
}

// Option is a Service's constructor option.
type Option func(*cfg)

// NetworkInfo wraps network state and configurations.
type NetworkInfo interface {
	netmap.State

	// Must return the lifespan of the tombstones
	// in the FrostFS epochs.
	TombstoneLifetime() (uint64, error)

	// Returns user ID of the local storage node. Result must not be nil.
	// New tombstone objects will have the result as an owner ID if removal is executed w/o a session.
	LocalNodeID() user.ID
}

type cfg struct {
	log *logger.Logger

	header interface {
		// must return (nil, nil) for PHY objects
		head(context.Context, *execCtx) (*objectSDK.Object, error)

		children(context.Context, *execCtx) ([]oid.ID, error)

		// must return (nil, nil) for 1st object in chain
		previous(context.Context, *execCtx, oid.ID) (*oid.ID, error)
	}

	searcher interface {
		splitMembers(context.Context, *execCtx) ([]oid.ID, error)
	}

	placer interface {
		put(context.Context, *execCtx) (*oid.ID, error)
	}

	netInfo NetworkInfo

	keyStorage *util.KeyStorage
}

// New creates, initializes and returns utility serving
// Object.Get service requests.
func New(gs *getsvc.Service,
	ss *searchsvc.Service,
	ps *putsvc.Service,
	ni NetworkInfo,
	ks *util.KeyStorage,
	opts ...Option,
) *Service {
	c := &cfg{
		log:        &logger.Logger{Logger: zap.L()},
		header:     &headSvcWrapper{s: gs},
		searcher:   &searchSvcWrapper{s: ss},
		placer:     &putSvcWrapper{s: ps},
		netInfo:    ni,
		keyStorage: ks,
	}

	for i := range opts {
		opts[i](c)
	}

	return &Service{
		cfg: c,
	}
}

// WithLogger returns option to specify Delete service's logger.
func WithLogger(l *logger.Logger) Option {
	return func(c *cfg) {
		c.log = &logger.Logger{Logger: l.With(zap.String("component", "objectSDK.Delete service"))}
	}
}