// Code generated by protoc-gen-slc. DO NOT EDIT.
package server

import (
	"context"
	"git.apinb.com/bsm-sdk/core/vars"
	pb "bsm/full/module/social/feed/pb"
	gwRuntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"google.golang.org/protobuf/proto"
	"net/http"
	"os"
	"strings"
)

type Server struct {
	Grpc *grpc.Server
	Ctx  context.Context
	Mux  *gwRuntime.ServeMux
}

func New(addr string) *Server {
	srv := &Server{Ctx: context.Background(), Grpc: grpc.NewServer(), Mux: gwRuntime.NewServeMux(
		gwRuntime.WithForwardResponseRewriter(responseEnvelope),
	)}

	// register service to grpc.Server
	pb.RegisterPostServer(srv.Grpc, NewPostServer())
	pb.RegisterSettingServer(srv.Grpc, NewSettingServer())
	pb.RegisterTagServer(srv.Grpc, NewTagServer())
	pb.RegisterTimelineServer(srv.Grpc, NewTimelineServer())

	reflection.Register(srv.Grpc)

	// 将服务注册到Gateway
	opts := []grpc.DialOption{grpc.WithInsecure()}
	pb.RegisterPostHandlerFromEndpoint(srv.Ctx, srv.Mux, addr, opts)
	pb.RegisterSettingHandlerFromEndpoint(srv.Ctx, srv.Mux, addr, opts)
	pb.RegisterTagHandlerFromEndpoint(srv.Ctx, srv.Mux, addr, opts)
	pb.RegisterTimelineHandlerFromEndpoint(srv.Ctx, srv.Mux, addr, opts)

	// Register services swagger
	srv.RegisterSwagger()

	return srv
}

// RegisterSwagger 注册swagger
func (s *Server) RegisterSwagger() {
	srvKey := strings.ToLower(vars.ServiceKey)
	s.Mux.HandlePath("GET", "/"+srvKey+".swagger.json", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
		w.Header().Set("Content-Type", "application/json")
		bytes, err := os.ReadFile("./swagger/" + srvKey + ".swagger.json")
		if err != nil {
			w.WriteHeader(http.StatusNotFound)
			w.Write([]byte(err.Error()))
			return
		}
		w.Write(bytes)
		return

	})
}

// response envelope
func responseEnvelope(_ context.Context, response proto.Message) (interface{}, error) {
	name := string(response.ProtoReflect().Descriptor().Name())
	if name == "Status" || name == "Error" || name == "StatusReply" {
		return response, nil
	}
	return map[string]any{
		"code":    0,
		"message": "OK",
		"result":  response,
	}, nil
}
