// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package hybrid

import (
	"fmt"
	"slices"

	"github.com/tink-crypto/tink-go/v2/internal/factoryutil"
	"github.com/tink-crypto/tink-go/v2/internal/internalapi"
	"github.com/tink-crypto/tink-go/v2/internal/registryconfig"
	"github.com/tink-crypto/tink-go/v2/keyset"
	"github.com/tink-crypto/tink-go/v2/monitoring"
	"github.com/tink-crypto/tink-go/v2/tink"
)

// NewHybridEncrypt returns a [tink.HybridEncrypt] primitive from the given
// [keyset.Handle] using the global registry.
func NewHybridEncrypt(handle *keyset.Handle) (tink.HybridEncrypt, error) {
	return NewHybridEncryptWithConfig(handle, &registryconfig.RegistryConfig{})
}

// NewHybridEncryptWithConfig returns a [tink.HybridEncrypt] primitive from
// the given [keyset.Handle] and [keyset.Config].
//
// NOTE: [keyset.Config] is currently a type that can only be used internally;
// thus this function is not part of the public API.
func NewHybridEncryptWithConfig(handle *keyset.Handle, config keyset.Config) (tink.HybridEncrypt, error) {
	if handle.Len() == 0 {
		return nil, fmt.Errorf("hybrid_factory: empty or nil keyset handle")
	}
	// Make sure the primitives do not implement tink.AEAD.
	for entry := range factoryutil.EnabledUnmonitoredEntries(handle) {
		p, _, err := factoryutil.PrimitiveFromKey[tink.HybridEncrypt](entry.Key(), config)
		if err != nil {
			return nil, err
		}
		if isAEAD(p) {
			return nil, fmt.Errorf("hybrid_factory: primitive must NOT implement tink.AEAD")
		}
	}

	primaryEntry, err := handle.Primary()
	if err != nil {
		return nil, err
	}
	// Make sure this access doesn't get logged as key export.
	primaryEntry = primaryEntry.ToUnmonitoredEntry(internalapi.Token{})
	primitive, isLegacyPrimitive, err := factoryutil.PrimitiveFromKey[tink.HybridEncrypt](primaryEntry.Key(), config)
	if err != nil {
		return nil, err
	}
	if isLegacyPrimitive {
		outputPrefix, err := factoryutil.OutputPrefix(primaryEntry.Key())
		if err != nil {
			return nil, err
		}
		primitive = &fullHybridEncryptAdapter{
			rawHybridEncrypt: primitive,
			prefix:           outputPrefix,
		}
	}

	logger, err := createEncryptLogger(handle)
	if err != nil {
		return nil, err
	}
	return &wrappedHybridEncrypt{
		fullPrimitive: primitive,
		logger:        logger,
		keyID:         primaryEntry.KeyID(),
	}, nil
}

// fullHybridEncryptAdapter is an [tink.HybridEncrypt] implementation that
// makes a given RAW [tink.HybridEncrypt] a full primitive prepending the
// prefix the resulting ciphertext.
type fullHybridEncryptAdapter struct {
	rawHybridEncrypt tink.HybridEncrypt
	prefix           []byte
}

var _ tink.HybridEncrypt = (*fullHybridEncryptAdapter)(nil)

func (e *fullHybridEncryptAdapter) Encrypt(plaintext, contextInfo []byte) ([]byte, error) {
	ct, err := e.rawHybridEncrypt.Encrypt(plaintext, contextInfo)
	if err != nil {
		return nil, err
	}
	return slices.Concat(e.prefix, ct), nil
}

// encryptPrimitiveSet is an HybridEncrypt implementation that uses the underlying primitive set for encryption.
type wrappedHybridEncrypt struct {
	fullPrimitive tink.HybridEncrypt
	logger        monitoring.Logger
	keyID         uint32
}

// compile time assertion that wrappedHybridEncrypt implements the HybridEncrypt interface.
var _ tink.HybridEncrypt = (*wrappedHybridEncrypt)(nil)

// Encrypt encrypts the given plaintext binding contextInfo to the resulting ciphertext.
// It returns the concatenation of the primary's identifier and the ciphertext.
func (a *wrappedHybridEncrypt) Encrypt(plaintext, contextInfo []byte) ([]byte, error) {
	ct, err := a.fullPrimitive.Encrypt(plaintext, contextInfo)
	if err != nil {
		a.logger.LogFailure()
		return nil, err
	}
	a.logger.Log(a.keyID, len(plaintext))
	return ct, nil
}

func isAEAD(p any) bool {
	if p == nil {
		return false
	}
	_, ok := p.(tink.AEAD)
	return ok
}

func createEncryptLogger(kh *keyset.Handle) (monitoring.Logger, error) {
	factory, err := factoryutil.NewLoggerFactory(kh)
	if err != nil {
		return nil, err
	}
	return factory.CreateFor("hybrid_encrypt", "encrypt")
}
