// Code generated by goa v3.6.0, DO NOT EDIT.
//
// Service1 gRPC server
//
// Command:
// $ goa gen goa_example/design

package server

import (
	"context"
	"errors"
	service1pb "goa_example/gen/grpc/service1/pb"
	service1 "goa_example/gen/service1"

	goagrpc "goa.design/goa/v3/grpc"
	goa "goa.design/goa/v3/pkg"
	"google.golang.org/grpc/codes"
)

// Server implements the service1pb.Service1Server interface.
type Server struct {
	SigninH goagrpc.UnaryHandler
	SecureH goagrpc.UnaryHandler
	service1pb.UnimplementedService1Server
}

// ErrorNamer is an interface implemented by generated error structs that
// exposes the name of the error as defined in the expr.
type ErrorNamer interface {
	ErrorName() string
}

// New instantiates the server struct with the Service1 service endpoints.
func New(e *service1.Endpoints, uh goagrpc.UnaryHandler) *Server {
	return &Server{
		SigninH: NewSigninHandler(e.Signin, uh),
		SecureH: NewSecureHandler(e.Secure, uh),
	}
}

// NewSigninHandler creates a gRPC handler which serves the "Service1" service
// "signin" endpoint.
func NewSigninHandler(endpoint goa.Endpoint, h goagrpc.UnaryHandler) goagrpc.UnaryHandler {
	if h == nil {
		h = goagrpc.NewUnaryHandler(endpoint, DecodeSigninRequest, EncodeSigninResponse)
	}
	return h
}

// Signin implements the "Signin" method in service1pb.Service1Server interface.
func (s *Server) Signin(ctx context.Context, message *service1pb.SigninRequest) (*service1pb.SigninResponse, error) {
	ctx = context.WithValue(ctx, goa.MethodKey, "signin")
	ctx = context.WithValue(ctx, goa.ServiceKey, "Service1")
	resp, err := s.SigninH.Handle(ctx, message)
	if err != nil {
		var en ErrorNamer
		if errors.As(err, &en) {
			switch en.ErrorName() {
			case "unauthorized":
				return nil, goagrpc.NewStatusError(codes.Unauthenticated, err, goagrpc.NewErrorResponse(err))
			}
		}
		return nil, goagrpc.EncodeError(err)
	}
	return resp.(*service1pb.SigninResponse), nil
}

// NewSecureHandler creates a gRPC handler which serves the "Service1" service
// "secure" endpoint.
func NewSecureHandler(endpoint goa.Endpoint, h goagrpc.UnaryHandler) goagrpc.UnaryHandler {
	if h == nil {
		h = goagrpc.NewUnaryHandler(endpoint, DecodeSecureRequest, EncodeSecureResponse)
	}
	return h
}

// Secure implements the "Secure" method in service1pb.Service1Server interface.
func (s *Server) Secure(ctx context.Context, message *service1pb.SecureRequest) (*service1pb.SecureResponse, error) {
	ctx = context.WithValue(ctx, goa.MethodKey, "secure")
	ctx = context.WithValue(ctx, goa.ServiceKey, "Service1")
	resp, err := s.SecureH.Handle(ctx, message)
	if err != nil {
		var en ErrorNamer
		if errors.As(err, &en) {
			switch en.ErrorName() {
			case "unauthorized":
				return nil, goagrpc.NewStatusError(codes.Unauthenticated, err, goagrpc.NewErrorResponse(err))
			}
		}
		return nil, goagrpc.EncodeError(err)
	}
	return resp.(*service1pb.SecureResponse), nil
}