package container

import (
	"fmt"

	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client"
	"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/event"
	"github.com/nspcc-dev/neo-go/pkg/core/state"
	"github.com/nspcc-dev/neo-go/pkg/network/payload"
)

// SetEACL represents structure of notification about
// modified eACL table coming from FrostFS Container contract.
type SetEACL struct {
	TableValue     []byte
	SignatureValue []byte
	PublicKeyValue []byte
	TokenValue     []byte

	// For notary notifications only.
	// Contains raw transactions of notary request.
	NotaryRequestValue *payload.P2PNotaryRequest
}

// MorphEvent implements Neo:Morph Event interface.
func (SetEACL) MorphEvent() {}

// Table returns returns eACL table in a binary FrostFS API format.
func (x SetEACL) Table() []byte {
	return x.TableValue
}

// Signature returns signature of the binary table.
func (x SetEACL) Signature() []byte {
	return x.SignatureValue
}

// PublicKey returns public keys of container
// owner in a binary format.
func (x SetEACL) PublicKey() []byte {
	return x.PublicKeyValue
}

// SessionToken returns binary token of the session
// within which the eACL was set.
func (x SetEACL) SessionToken() []byte {
	return x.TokenValue
}

// NotaryRequest returns raw notary request if notification
// was received via notary service. Otherwise, returns nil.
func (x SetEACL) NotaryRequest() *payload.P2PNotaryRequest {
	return x.NotaryRequestValue
}

const expectedItemNumEACL = 4

// ParseSetEACL parses SetEACL notification event from list of stack items.
//
// Expects 4 stack items.
func ParseSetEACL(e *state.ContainedNotificationEvent) (event.Event, error) {
	var (
		ev  SetEACL
		err error
	)

	params, err := event.ParseStackArray(e)
	if err != nil {
		return nil, fmt.Errorf("could not parse stack items from notify event: %w", err)
	}

	if ln := len(params); ln != expectedItemNumEACL {
		return nil, event.WrongNumberOfParameters(expectedItemNumEACL, ln)
	}

	// parse table
	ev.TableValue, err = client.BytesFromStackItem(params[0])
	if err != nil {
		return nil, fmt.Errorf("could not parse binary table: %w", err)
	}

	// parse signature
	ev.SignatureValue, err = client.BytesFromStackItem(params[1])
	if err != nil {
		return nil, fmt.Errorf("could not parse table signature: %w", err)
	}

	// parse public key
	ev.PublicKeyValue, err = client.BytesFromStackItem(params[2])
	if err != nil {
		return nil, fmt.Errorf("could not parse binary public key: %w", err)
	}

	// parse session token
	ev.TokenValue, err = client.BytesFromStackItem(params[3])
	if err != nil {
		return nil, fmt.Errorf("could not get session token: %w", err)
	}

	return ev, nil
}