package writecache

import (
	"context"

	"git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/pkg/tracing"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/local_object_storage/blobstor/common"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/local_object_storage/util/logicerr"
	apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
	objectSDK "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object"
	oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
	"github.com/nspcc-dev/neo-go/pkg/util/slice"
	"go.etcd.io/bbolt"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"
)

// Get returns object from write-cache.
//
// Returns an error of type apistatus.ObjectNotFound if the requested object is missing in write-cache.
func (c *cache) Get(ctx context.Context, addr oid.Address) (*objectSDK.Object, error) {
	saddr := addr.EncodeToString()

	ctx, span := tracing.StartSpanFromContext(ctx, "writecache.Get",
		trace.WithAttributes(
			attribute.String("address", saddr),
		))
	defer span.End()

	value, err := Get(c.db, []byte(saddr))
	if err == nil {
		obj := objectSDK.New()
		c.flushed.Get(saddr)
		return obj, obj.Unmarshal(value)
	}

	res, err := c.fsTree.Get(ctx, common.GetPrm{Address: addr})
	if err != nil {
		return nil, logicerr.Wrap(apistatus.ObjectNotFound{})
	}

	c.flushed.Get(saddr)
	return res.Object, nil
}

// Head returns object header from write-cache.
//
// Returns an error of type apistatus.ObjectNotFound if the requested object is missing in write-cache.
func (c *cache) Head(ctx context.Context, addr oid.Address) (*objectSDK.Object, error) {
	ctx, span := tracing.StartSpanFromContext(ctx, "writecache.Head",
		trace.WithAttributes(
			attribute.String("address", addr.EncodeToString()),
		))
	defer span.End()

	obj, err := c.Get(ctx, addr)
	if err != nil {
		return nil, err
	}

	return obj.CutPayload(), nil
}

// Get fetches object from the underlying database.
// Key should be a stringified address.
//
// Returns an error of type apistatus.ObjectNotFound if the requested object is missing in db.
func Get(db *bbolt.DB, key []byte) ([]byte, error) {
	var value []byte
	err := db.View(func(tx *bbolt.Tx) error {
		b := tx.Bucket(defaultBucket)
		if b == nil {
			return ErrNoDefaultBucket
		}
		value = b.Get(key)
		if value == nil {
			return logicerr.Wrap(apistatus.ObjectNotFound{})
		}
		value = slice.Copy(value)
		return nil
	})
	return value, err
}