package keydirectory

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/ed25519"
	"crypto/rsa"
	"fmt"
	"reflect"

	"github.com/common-fate/httpsig/alg_ecdsa"
	"github.com/common-fate/httpsig/alg_ed25519"
	"github.com/common-fate/httpsig/alg_rsa"
	"github.com/common-fate/httpsig/verifier"
)

type keyEntry struct {
	PublicKey crypto.PublicKey
	UserId    string
}

func (k keyEntry) toAlg() (verifier.Algorithm, error) {
	var alg verifier.Algorithm
	var err error

	switch k.PublicKey.(type) {
	case ed25519.PublicKey:
		alg = alg_ed25519.Ed25519{
			PublicKey: k.PublicKey.(ed25519.PublicKey),
			Attrs:     k.UserId,
		}
	case *rsa.PublicKey:
		alg = alg_rsa.RSAPKCS256{
			PublicKey: k.PublicKey.(*rsa.PublicKey),
			Attrs:     k.UserId,
		}
	case *ecdsa.PublicKey:
		alg = alg_ecdsa.P256{
			PublicKey: k.PublicKey.(*ecdsa.PublicKey),
			Attrs:     k.UserId,
		}
	default:
		err = fmt.Errorf("unknown key type: %s", reflect.TypeOf(k.PublicKey))
	}

	return alg, err
}