package ape

import (
	"errors"
	"fmt"

	apeV2 "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/ape"
)

var (
	ErrInvalidChainRepresentation = errors.New("invalid chain representation")
)

// ChainID is Chain's identifier.
type ChainID []byte

// Chain is an SDK representation for v2's Chain.
//
// Note that Chain (as well as v2's Chain) and all related entities
// are NOT operated by Access-Policy-Engine (APE). The client is responsible
// to convert these types to policy-engine entities.
type Chain struct {
	// Raw is the encoded chain kind.
	// It assumes that Raw's bytes are the result of encoding provided by
	// policy-engine package.
	Raw []byte
}

// ToV2 converts Chain to v2.
func (c *Chain) ToV2() *apeV2.Chain {
	v2ct := new(apeV2.Chain)

	if c.Raw != nil {
		v2Raw := new(apeV2.ChainRaw)
		v2Raw.SetRaw(c.Raw)
		v2ct.SetKind(v2Raw)
	}

	return v2ct
}

// ReadFromV2 fills Chain from v2.
func (c *Chain) ReadFromV2(v2ct *apeV2.Chain) error {
	switch v := v2ct.GetKind().(type) {
	default:
		return fmt.Errorf("unsupported chain kind: %T", v)
	case *apeV2.ChainRaw:
		raw := v.GetRaw()
		c.Raw = raw
	}
	return nil
}