package engine

import (
	"github.com/nspcc-dev/neofs-node/pkg/local_object_storage/shard"
	apistatus "github.com/nspcc-dev/neofs-sdk-go/client/status"
	oid "github.com/nspcc-dev/neofs-sdk-go/object/id"
	"go.uber.org/zap"
)

// DeletePrm groups the parameters of Delete operation.
type DeletePrm struct {
	addr oid.Address

	forceRemoval bool
}

// DeleteRes groups the resulting values of Delete operation.
type DeleteRes struct{}

// WithAddress is a Delete option to set the addresses of the objects to delete.
//
// Option is required.
func (p *DeletePrm) WithAddress(addr oid.Address) {
	p.addr = addr
}

// WithForceRemoval is a Delete option to remove an object despite any
// restrictions imposed on deleting that object. Expected to be used
// only in control service.
func (p *DeletePrm) WithForceRemoval() {
	p.forceRemoval = true
}

// Delete marks the objects to be removed.
//
// Returns an error if executions are blocked (see BlockExecution).
//
// Returns apistatus.ObjectLocked if at least one object is locked.
// In this case no object from the list is marked to be deleted.
//
// NOTE: Marks any object to be deleted (despite any prohibitions
// on operations with that object) if WithForceRemoval option has
// been provided.
func (e *StorageEngine) Delete(prm DeletePrm) (res DeleteRes, err error) {
	err = e.execIfNotBlocked(func() error {
		res, err = e.delete(prm)
		return err
	})

	return
}

func (e *StorageEngine) delete(prm DeletePrm) (DeleteRes, error) {
	if e.metrics != nil {
		defer elapsed(e.metrics.AddDeleteDuration)()
	}

	if !prm.forceRemoval {
		locked, err := e.isLocked(prm.addr)
		if err != nil {
			e.log.Warn("deleting an object without full locking check",
				zap.Error(err),
				zap.Stringer("addr", prm.addr))
		} else if locked {
			var lockedErr apistatus.ObjectLocked
			return DeleteRes{}, lockedErr
		}
	}

	var inhumePrm shard.InhumePrm
	inhumePrm.MarkAsGarbage(prm.addr)
	if prm.forceRemoval {
		inhumePrm.ForceRemoval()
	}

	_, err := e.inhumeAddr(prm.addr, inhumePrm)

	return DeleteRes{}, err
}
