// Copyright 2018 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 signature

import (
	"bytes"
	"fmt"
	"slices"

	"github.com/tink-crypto/tink-go/v2/core/cryptofmt"
	"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/protoserialization"
	"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"
	tinkpb "github.com/tink-crypto/tink-go/v2/proto/tink_go_proto"
)

// NewSignerWithConfig returns a [tink.Signer] primitive from the given
// [keyset.Handle] and [keyset.Config].
func NewSignerWithConfig(handle *keyset.Handle, config keyset.Config) (tink.Signer, error) {
	if handle.Len() == 0 {
		return nil, fmt.Errorf("signer_factory: empty or nil keyset handle")
	}
	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{})
	signer, isLegacyPrimitive, err := factoryutil.PrimitiveFromKey[tink.Signer](primaryEntry.Key(), config)
	if err != nil {
		return nil, err
	}
	if isLegacyPrimitive {
		hasLegacyPrefix := false
		outputPrefix, err := factoryutil.OutputPrefix(primaryEntry.Key())
		if err != nil {
			return nil, err
		}
		if bytes.HasPrefix(outputPrefix, []byte{cryptofmt.LegacyStartByte}) { // CRUNCHY or LEGACY
			protoKey, err := protoserialization.SerializeKey(primaryEntry.Key())
			if err != nil {
				return nil, err
			}
			hasLegacyPrefix = protoKey.OutputPrefixType() == tinkpb.OutputPrefixType_LEGACY
		}
		signer = &fullSignerAdapter{
			primitive:       signer,
			prefix:          outputPrefix,
			hasLegacyPrefix: hasLegacyPrefix,
		}
	}
	logger, err := createSignerLogger(handle)
	if err != nil {
		return nil, err
	}
	return &wrappedSigner{
		signer:      signer,
		signerKeyID: primaryEntry.KeyID(),
		logger:      logger,
	}, nil
}

// NewSigner returns a [tink.Signer] primitive from the given
// [keyset.Handle].
func NewSigner(handle *keyset.Handle) (tink.Signer, error) {
	return NewSignerWithConfig(handle, &registryconfig.RegistryConfig{})
}

// wrappedSigner is an Signer implementation that uses the underlying primitive set for signing.
type wrappedSigner struct {
	signer      tink.Signer
	signerKeyID uint32
	logger      monitoring.Logger
}

// Asserts that wrappedSigner implements the Signer interface.
var _ tink.Signer = (*wrappedSigner)(nil)

type fullSignerAdapter struct {
	primitive       tink.Signer
	prefix          []byte
	hasLegacyPrefix bool
}

var _ tink.Signer = (*fullSignerAdapter)(nil)

func (a *fullSignerAdapter) Sign(data []byte) ([]byte, error) {
	toSign := data
	if a.hasLegacyPrefix {
		toSign = slices.Concat(data, []byte{0})
	}
	s, err := a.primitive.Sign(toSign)
	if err != nil {
		return nil, err
	}
	return slices.Concat(a.prefix, s), nil
}

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

// Sign signs the given data using the primary key.
func (s *wrappedSigner) Sign(data []byte) ([]byte, error) {
	signature, err := s.signer.Sign(data)
	if err != nil {
		s.logger.LogFailure()
		return nil, err
	}
	s.logger.Log(s.signerKeyID, len(data))
	return signature, nil
}
