package blobstor

import (
	"context"
	"encoding/hex"
	"errors"

	"git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/pkg/tracing"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/local_object_storage/blobstor/common"
	apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"
)

func (b *BlobStor) Delete(ctx context.Context, prm common.DeletePrm) (common.DeleteRes, error) {
	ctx, span := tracing.StartSpanFromContext(ctx, "BlobStor.Delete",
		trace.WithAttributes(
			attribute.String("address", prm.Address.EncodeToString()),
			attribute.String("storage_id", hex.EncodeToString(prm.StorageID)),
		))
	defer span.End()

	b.modeMtx.RLock()
	defer b.modeMtx.RUnlock()

	if prm.StorageID == nil {
		for i := range b.storage {
			res, err := b.storage[i].Storage.Delete(ctx, prm)
			if err == nil || !errors.As(err, new(apistatus.ObjectNotFound)) {
				if err == nil {
					logOp(b.log, deleteOp, prm.Address, b.storage[i].Storage.Type(), prm.StorageID)
				}
				return res, err
			}
		}
	}

	var st common.Storage

	if len(prm.StorageID) == 0 {
		st = b.storage[len(b.storage)-1].Storage
	} else {
		st = b.storage[0].Storage
	}

	res, err := st.Delete(ctx, prm)
	if err == nil {
		logOp(b.log, deleteOp, prm.Address, st.Type(), prm.StorageID)
	}

	return res, err
}