package tree

import (
	"context"
	"crypto/ecdsa"
	"encoding/hex"
	"errors"
	"fmt"
	"net"
	"strings"

	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/ape/converter"
	aperequest "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/ape/request"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/ape/router"
	core "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/core/container"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/core/netmap"
	"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/ape"
	"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/bearer"
	apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
	cnrSDK "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container"
	"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/acl"
	cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
	"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/user"
	apechain "git.frostfs.info/TrueCloudLab/policy-engine/pkg/chain"
	"git.frostfs.info/TrueCloudLab/policy-engine/pkg/engine"
	commonschema "git.frostfs.info/TrueCloudLab/policy-engine/schema/common"
	nativeschema "git.frostfs.info/TrueCloudLab/policy-engine/schema/native"
	"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
	"google.golang.org/grpc/peer"
)

var (
	errInvalidTargetType        = errors.New("bearer token defines non-container target override")
	errBearerExpired            = errors.New("bearer token has expired")
	errBearerInvalidSignature   = errors.New("bearer token has invalid signature")
	errBearerInvalidContainerID = errors.New("bearer token was created for another container")
	errBearerNotSignedByOwner   = errors.New("bearer token is not signed by the container owner")
	errBearerInvalidOwner       = errors.New("bearer token owner differs from the request sender")
)

func (s *Service) newAPERequest(ctx context.Context, namespace string,
	cid cid.ID, operation acl.Op, role acl.Role, publicKey *keys.PublicKey,
) (aperequest.Request, error) {
	schemaMethod, err := converter.SchemaMethodFromACLOperation(operation)
	if err != nil {
		return aperequest.Request{}, err
	}
	schemaRole, err := converter.SchemaRoleFromACLRole(role)
	if err != nil {
		return aperequest.Request{}, err
	}
	reqProps := map[string]string{
		nativeschema.PropertyKeyActorPublicKey: hex.EncodeToString(publicKey.Bytes()),
		nativeschema.PropertyKeyActorRole:      schemaRole,
	}
	reqProps, err = s.fillWithUserClaimTags(reqProps, publicKey)
	if err != nil {
		return aperequest.Request{}, err
	}
	if p, ok := peer.FromContext(ctx); ok {
		if tcpAddr, ok := p.Addr.(*net.TCPAddr); ok {
			reqProps[commonschema.PropertyKeyFrostFSSourceIP] = tcpAddr.IP.String()
		}
	}

	var resourceName string
	if namespace == "root" || namespace == "" {
		resourceName = fmt.Sprintf(nativeschema.ResourceFormatRootContainerObjects, cid.EncodeToString())
	} else {
		resourceName = fmt.Sprintf(nativeschema.ResourceFormatNamespaceContainerObjects, namespace, cid.EncodeToString())
	}

	return aperequest.NewRequest(
		schemaMethod,
		aperequest.NewResource(resourceName, make(map[string]string)),
		reqProps,
	), nil
}

// isValidBearer checks whether bearer token was correctly signed by authorized
// entity. This method might be defined on whole ACL service because it will
// require fetching current epoch to check lifetime.
func isValidBearer(token *bearer.Token, ownerCnr user.ID, cntID cid.ID, publicKey *keys.PublicKey, st netmap.State) error {
	if token == nil {
		return nil
	}

	// First check token lifetime. Simplest verification.
	if token.InvalidAt(st.CurrentEpoch()) {
		return errBearerExpired
	}

	// Then check if bearer token is signed correctly.
	if !token.VerifySignature() {
		return errBearerInvalidSignature
	}

	// Check for ape overrides defined in the bearer token.
	apeOverride := token.APEOverride()
	if len(apeOverride.Chains) > 0 && apeOverride.Target.TargetType != ape.TargetTypeContainer {
		return fmt.Errorf("%w: %s", errInvalidTargetType, apeOverride.Target.TargetType.ToV2().String())
	}

	// Then check if container is either empty or equal to the container in the request.
	var targetCnr cid.ID
	err := targetCnr.DecodeString(apeOverride.Target.Name)
	if err != nil {
		return fmt.Errorf("invalid cid format: %s", apeOverride.Target.Name)
	}
	if !cntID.Equals(targetCnr) {
		return errBearerInvalidContainerID
	}

	// Then check if container owner signed this token.
	if !bearer.ResolveIssuer(*token).Equals(ownerCnr) {
		return errBearerNotSignedByOwner
	}

	// Then check if request sender has rights to use this token.
	var usrSender user.ID
	user.IDFromKey(&usrSender, (ecdsa.PublicKey)(*publicKey))

	if !token.AssertUser(usrSender) {
		return errBearerInvalidOwner
	}

	return nil
}

func (s *Service) checkAPE(ctx context.Context, bt *bearer.Token,
	container *core.Container, cid cid.ID, operation acl.Op, role acl.Role, publicKey *keys.PublicKey,
) error {
	namespace := ""
	cntNamespace, hasNamespace := strings.CutSuffix(cnrSDK.ReadDomain(container.Value).Zone(), ".ns")
	if hasNamespace {
		namespace = cntNamespace
	}

	request, err := s.newAPERequest(ctx, namespace, cid, operation, role, publicKey)
	if err != nil {
		return apeErr(err)
	}

	var cr engine.ChainRouter
	if bt != nil && !bt.Impersonate() {
		if err := isValidBearer(bt, container.Value.Owner(), cid, publicKey, s.state); err != nil {
			return fmt.Errorf("bearer validation error: %w", err)
		}
		cr, err = router.BearerChainFeedRouter(s.localOverrideStorage, s.morphChainStorage, bt.APEOverride())
		if err != nil {
			return fmt.Errorf("create chain router error: %w", err)
		}
	} else {
		cr = engine.NewDefaultChainRouterWithLocalOverrides(s.morphChainStorage, s.localOverrideStorage)
	}

	groups, err := aperequest.Groups(s.frostfsidSubjectProvider, publicKey)
	if err != nil {
		return fmt.Errorf("failed to get group ids: %w", err)
	}

	// Policy contract keeps group related chains as namespace-group pair.
	for i := range groups {
		groups[i] = fmt.Sprintf("%s:%s", namespace, groups[i])
	}

	rt := engine.NewRequestTargetExtended(namespace, cid.EncodeToString(), fmt.Sprintf("%s:%s", namespace, publicKey.Address()), groups)
	status, found, err := cr.IsAllowed(apechain.Ingress, rt, request)
	if err != nil {
		return apeErr(err)
	}
	if found && status == apechain.Allow {
		return nil
	}
	err = fmt.Errorf("access to operation %s is denied by access policy engine: %s", request.Operation(), status.String())
	return apeErr(err)
}

func apeErr(err error) error {
	errAccessDenied := &apistatus.ObjectAccessDenied{}
	errAccessDenied.WriteReason(err.Error())
	return errAccessDenied
}

// fillWithUserClaimTags fills ape request properties with user claim tags getting them from frostfsid contract by actor public key.
func (s *Service) fillWithUserClaimTags(reqProps map[string]string, publicKey *keys.PublicKey) (map[string]string, error) {
	if reqProps == nil {
		reqProps = make(map[string]string)
	}
	props, err := aperequest.FormFrostfsIDRequestProperties(s.frostfsidSubjectProvider, publicKey)
	if err != nil {
		return reqProps, err
	}
	for propertyName, properyValue := range props {
		reqProps[propertyName] = properyValue
	}
	return reqProps, nil
}