package grpcapi

import (
	"context"
	"errors"

	"galaxy/gateway/authn"
	edgev1 "galaxy/gateway/proto/edge/v1"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// payloadHashVerifyingService applies payload-hash verification after
// client-signature verification and before any later auth or routing step runs.
type payloadHashVerifyingService struct {
	edgev1.UnimplementedGatewayServer

	delegate edgev1.GatewayServer
}

// ExecuteCommand verifies req payload integrity before delegating to the
// configured service implementation.
func (s payloadHashVerifyingService) ExecuteCommand(ctx context.Context, req *edgev1.ExecuteCommandRequest) (*edgev1.ExecuteCommandResponse, error) {
	if err := verifyPayloadHash(ctx); err != nil {
		return nil, err
	}

	return s.delegate.ExecuteCommand(ctx, req)
}

// SubscribeEvents verifies req payload integrity before delegating to the
// configured service implementation.
func (s payloadHashVerifyingService) SubscribeEvents(req *edgev1.SubscribeEventsRequest, stream grpc.ServerStreamingServer[edgev1.GatewayEvent]) error {
	if err := verifyPayloadHash(stream.Context()); err != nil {
		return err
	}

	return s.delegate.SubscribeEvents(req, stream)
}

// newPayloadHashVerifyingService wraps delegate with the payload-hash
// verification gate.
func newPayloadHashVerifyingService(delegate edgev1.GatewayServer) edgev1.GatewayServer {
	return payloadHashVerifyingService{delegate: delegate}
}

func verifyPayloadHash(ctx context.Context) error {
	envelope, ok := parsedEnvelopeFromContext(ctx)
	if !ok {
		return status.Error(codes.Internal, "authenticated request context is incomplete")
	}

	err := authn.VerifyPayloadHash(envelope.PayloadBytes, envelope.PayloadHash)
	switch {
	case err == nil:
		return nil
	case errors.Is(err, authn.ErrInvalidPayloadHash), errors.Is(err, authn.ErrPayloadHashMismatch):
		return status.Error(codes.InvalidArgument, err.Error())
	default:
		return status.Error(codes.Internal, "payload hash verification failed")
	}
}

var _ edgev1.GatewayServer = payloadHashVerifyingService{}
