// Copyright 2024 The Sigstore Authors.
//
// 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 bundle

import (
	"crypto"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"fmt"

	"github.com/secure-systems-lab/go-securesystemslib/dsse"
	protobundle "github.com/sigstore/protobuf-specs/gen/pb-go/bundle/v1"
	protocommon "github.com/sigstore/protobuf-specs/gen/pb-go/common/v1"
	protodsse "github.com/sigstore/protobuf-specs/gen/pb-go/dsse"
	protorekor "github.com/sigstore/protobuf-specs/gen/pb-go/rekor/v1"
	"github.com/sigstore/rekor/pkg/generated/models"
	"github.com/sigstore/rekor/pkg/tle"
	"github.com/sigstore/sigstore/pkg/cryptoutils"
	"google.golang.org/protobuf/encoding/protojson"
)

const BundleV03MediaType = "application/vnd.dev.sigstore.bundle.v0.3+json"

func MakeProtobufBundle(hint string, rawCert []byte, rekorEntry *models.LogEntryAnon, timestampBytes []byte) (*protobundle.Bundle, error) {
	bundle := &protobundle.Bundle{MediaType: BundleV03MediaType}

	if hint != "" {
		bundle.VerificationMaterial = &protobundle.VerificationMaterial{
			Content: &protobundle.VerificationMaterial_PublicKey{
				PublicKey: &protocommon.PublicKeyIdentifier{
					Hint: hint,
				},
			},
		}
	} else if len(rawCert) > 0 {
		bundle.VerificationMaterial = &protobundle.VerificationMaterial{
			Content: &protobundle.VerificationMaterial_Certificate{
				Certificate: &protocommon.X509Certificate{
					RawBytes: rawCert,
				},
			},
		}
	}

	if len(timestampBytes) > 0 {
		bundle.VerificationMaterial.TimestampVerificationData = &protobundle.TimestampVerificationData{
			Rfc3161Timestamps: []*protocommon.RFC3161SignedTimestamp{
				{SignedTimestamp: timestampBytes},
			},
		}
	}

	if rekorEntry != nil {
		tlogEntry, err := tle.GenerateTransparencyLogEntry(*rekorEntry)
		if err != nil {
			return nil, err
		}
		bundle.VerificationMaterial.TlogEntries = []*protorekor.TransparencyLogEntry{tlogEntry}
	}

	return bundle, nil
}

func MakeNewBundle(pubKey crypto.PublicKey, rekorEntry *models.LogEntryAnon, payload, sig, signer, timestampBytes []byte) ([]byte, error) {
	// Determine if the signer is a certificate or not
	var hint string
	var rawCert []byte

	cert, err := cryptoutils.UnmarshalCertificatesFromPEM(signer)
	if err != nil || len(cert) == 0 {
		pkixPubKey, err := x509.MarshalPKIXPublicKey(pubKey)
		if err != nil {
			return nil, err
		}
		hashedBytes := sha256.Sum256(pkixPubKey)
		hint = base64.StdEncoding.EncodeToString(hashedBytes[:])
	} else {
		rawCert = cert[0].Raw
	}

	bundle, err := MakeProtobufBundle(hint, rawCert, rekorEntry, timestampBytes)
	if err != nil {
		return nil, err
	}

	var envelope dsse.Envelope
	err = json.Unmarshal(sig, &envelope)
	if err != nil {
		return nil, err
	}

	if len(envelope.Signatures) == 0 {
		return nil, fmt.Errorf("no signature in DSSE envelope")
	}

	sigBytes, err := base64.StdEncoding.DecodeString(envelope.Signatures[0].Sig)
	if err != nil {
		return nil, err
	}

	bundle.Content = &protobundle.Bundle_DsseEnvelope{
		DsseEnvelope: &protodsse.Envelope{
			Payload:     payload,
			PayloadType: envelope.PayloadType,
			Signatures: []*protodsse.Signature{
				{
					Sig: sigBytes,
				},
			},
		},
	}

	contents, err := protojson.Marshal(bundle)
	if err != nil {
		return nil, err
	}

	return contents, nil
}
