// Copyright (C) 2019-2025, Lux Industries Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package message

import (
	"fmt"

	"github.com/luxfi/crypto/bls"
	"github.com/luxfi/ids"
	"github.com/luxfi/crypto/hash"
	"github.com/luxfi/vm/types"
)

type ChainToL1ConversionValidatorData struct {
	NodeID       types.JSONByteSlice    `serialize:"true" json:"nodeID"`
	BLSPublicKey [bls.PublicKeyLen]byte `serialize:"true" json:"blsPublicKey"`
	Weight       uint64                 `serialize:"true" json:"weight"`
}

type ChainToL1ConversionData struct {
	ChainID        ids.ID                             `serialize:"true" json:"chainID"`
	ManagerChainID ids.ID                             `serialize:"true" json:"managerChainID"`
	ManagerAddress types.JSONByteSlice                `serialize:"true" json:"managerAddress"`
	Validators     []ChainToL1ConversionValidatorData `serialize:"true" json:"validators"`
}

// ChainToL1ConversionID creates a chain conversion ID from the provided
// chain conversion data.
func ChainToL1ConversionID(data ChainToL1ConversionData) (ids.ID, error) {
	bytes, err := Codec.Marshal(CodecVersion, &data)
	if err != nil {
		return ids.Empty, err
	}
	return hash.ComputeHash256Array(bytes), nil
}

// ChainToL1Conversion reports the summary of the chain conversion that
// occurred on the P-chain.
type ChainToL1Conversion struct {
	payload

	// ID of the chain conversion. It is typically generated by calling
	// ChainToL1ConversionID.
	ID ids.ID `serialize:"true" json:"id"`
}

// NewChainToL1Conversion creates a new initialized ChainToL1Conversion.
func NewChainToL1Conversion(id ids.ID) (*ChainToL1Conversion, error) {
	msg := &ChainToL1Conversion{
		ID: id,
	}
	return msg, Initialize(msg)
}

// ParseChainToL1Conversion parses bytes into an initialized
// ChainToL1Conversion.
func ParseChainToL1Conversion(b []byte) (*ChainToL1Conversion, error) {
	payloadIntf, err := Parse(b)
	if err != nil {
		return nil, err
	}
	payload, ok := payloadIntf.(*ChainToL1Conversion)
	if !ok {
		return nil, fmt.Errorf("%w: %T", ErrWrongType, payloadIntf)
	}
	return payload, nil
}
