package meta

import (
	"context"
	"time"

	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/local_object_storage/internal/metaerr"
	"git.frostfs.info/TrueCloudLab/frostfs-observability/tracing"
	oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
	"go.etcd.io/bbolt"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"
)

// GetChildren returns parent -> children map.
// If an object has no children, then map will contain addr -> empty slice value.
func (db *DB) GetChildren(ctx context.Context, addresses []oid.Address) (map[oid.Address][]oid.Address, error) {
	var (
		startedAt = time.Now()
		success   = false
	)
	defer func() {
		db.metrics.AddMethodDuration("GetChildren", time.Since(startedAt), success)
	}()

	_, span := tracing.StartSpanFromContext(ctx, "metabase.GetChildren",
		trace.WithAttributes(
			attribute.Int("addr_count", len(addresses)),
		))
	defer span.End()

	db.modeMtx.RLock()
	defer db.modeMtx.RUnlock()

	if db.mode.NoMetabase() {
		return nil, ErrDegradedMode
	}

	result := make(map[oid.Address][]oid.Address, len(addresses))

	buffer := make([]byte, bucketKeySize)
	err := db.boltDB.View(func(tx *bbolt.Tx) error {
		for _, addr := range addresses {
			if _, found := result[addr]; found {
				continue
			}

			result[addr] = []oid.Address{}
			bkt := tx.Bucket(parentBucketName(addr.Container(), buffer))
			if bkt == nil {
				continue
			}

			binObjIDs, err := decodeList(bkt.Get(objectKey(addr.Object(), buffer)))
			if err != nil {
				return err
			}

			for _, binObjID := range binObjIDs {
				var id oid.ID
				if err = id.Decode(binObjID); err != nil {
					return err
				}
				var resultAddress oid.Address
				resultAddress.SetContainer(addr.Container())
				resultAddress.SetObject(id)
				result[addr] = append(result[addr], resultAddress)
			}
		}
		return nil
	})
	if err != nil {
		return nil, metaerr.Wrap(err)
	}
	success = true
	return result, nil
}