package tools

import (
	"context"
	"crypto/sha512"
	"encoding/base64"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
)

const DigestKey = "Digest"

func ProxyMedataFromContext(context context.Context, request []byte) (context.Context, error) {
	md, ok := metadata.FromIncomingContext(context)
	md = md.Copy()
	digest := md.Get(DigestKey)
	if len(digest) == 0 {
		return nil, CreateError(codes.FailedPrecondition, "Can`t get metadata from context", "Missing Digest")
	}

	hashed := sha512.New()
	hashed.Write(request)
	output := hashed.Sum(nil)
	requestDigest := base64.StdEncoding.EncodeToString(output)

	if digest[0] != requestDigest {
		return nil, CreateError(codes.FailedPrecondition, "Digest is not equal to request body", "Invalid Digest")
	}

	if !ok {
		return nil, CreateError(codes.Unauthenticated, "Can`t get metadata from context", "Missing JWT")
	}
	return metadata.NewOutgoingContext(context, md), nil
}
