package subnetevents

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/util"
)

// Delete structures information about the notification generated by Delete method of Subnet contract.
type Delete struct {
	txHash util.Uint256

	id []byte
}

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

// ID returns identifier of the removed subnet in a binary format of NeoFS API protocol.
func (x Delete) ID() []byte {
	return x.id
}

// TxHash returns hash of the transaction which thrown the notification event.
// Makes sense only in notary environments.
func (x Delete) TxHash() util.Uint256 {
	return x.txHash
}

// ParseDelete parses the notification about the removal of a subnet which has been thrown
// by the appropriate method of the Subnet contract.
//
// Resulting event is of Delete type.
func ParseDelete(e *state.ContainedNotificationEvent) (event.Event, error) {
	var (
		ev  Delete
		err error
	)

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

	const itemNumDelete = 1

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

	// parse ID
	ev.id, err = client.BytesFromStackItem(items[0])
	if err != nil {
		return nil, fmt.Errorf("id item: %w", err)
	}

	ev.txHash = e.Container

	return ev, nil
}