package sharedmodel

import (
	"crypto"
	"fmt"

	"gorm.io/gorm"
	"src.whiteboxsystems.nl/DECOZO/okapi"
	"src.whiteboxsystems.nl/DECOZO/okapidemo/certgen"
)

type RegistrationStatus string

const (
	RegistrationStatusPending   = RegistrationStatus("pending")
	RegistrationStatusCompleted = RegistrationStatus("completed")
)

type Registration struct {
	gorm.Model
	OrganisationIdentifier     string
	OrganisationIdentifierType string
	OrganisationDisplayName    string
	AuthConfigID               uint
	AuthConfig                 *XISAuthConfig
	Reference                  string
	PSK                        string
	Status                     RegistrationStatus
}

func (r *Registration) SetAuthConfig(cfg *okapi.XISAuthConfiguration) error {
	authConfig := &XISAuthConfig{
		Method: int32(cfg.Method),
	}

	switch cfg.Method {
	case okapi.XISAuthMethod_mTLS:
		k, err := certgen.StringToJWK(cfg.GetMtlsConfiguration().GetPublicKey())

		if err != nil {
			return err
		}

		tp, err := k.Thumbprint(crypto.SHA256)

		if err != nil {
			return err
		}

		authConfig.Raw = fmt.Sprintf("%X", tp)
	}

	r.AuthConfig = authConfig

	return nil
}
