package managedkey

import (
	"context"
	"math/big"

	"github.com/ethereum/go-ethereum/core/types"
	"github.com/tech/sendico/pkg/mlogger"
)

// Config describes how to connect to Vault for managed wallet keys.
type Config struct {
	Address      string `mapstructure:"address" yaml:"address"`
	TokenEnv     string `mapstructure:"token_env" yaml:"token_env"`
	TokenFileEnv string `mapstructure:"token_file_env" yaml:"token_file_env"`
	TokenFile    string `mapstructure:"token_file" yaml:"token_file"`
	Namespace    string `mapstructure:"namespace" yaml:"namespace"`
	MountPath    string `mapstructure:"mount_path" yaml:"mount_path"`
	KeyPrefix    string `mapstructure:"key_prefix" yaml:"key_prefix"`
}

// ManagedWalletKey captures metadata returned after key provisioning.
type ManagedWalletKey struct {
	KeyID     string
	Address   string
	PublicKey string
}

// Material contains key material loaded from Vault.
type Material struct {
	PrivateKey string
	PublicKey  string
	Address    string
	Network    string
}

// Service defines managed key operations shared by gateways.
type Service interface {
	CreateManagedWalletKey(ctx context.Context, walletRef, network string) (*ManagedWalletKey, error)
	SignEVMTransaction(ctx context.Context, keyID string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error)
	LoadKeyMaterial(ctx context.Context, keyID string) (*Material, error)
	BuildKeyID(network, walletRef string) string
}

// Options configure managed key service creation.
type Options struct {
	Logger           mlogger.Logger
	Config           Config
	Component        string
	DefaultKeyPrefix string
}

// New creates a managed wallet key service backed by Vault KV.
func New(opts Options) (Service, error) {
	return newService(opts)
}
