package grpc

import (
	"github.com/pocketbase/pocketbase"
	"google.golang.org/grpc/keepalive"
	"log"
	"net"
	"time"

	"google.golang.org/grpc"
	pb "htwkalender/common/genproto/modules"
)

func StartGRPCServer(app *pocketbase.PocketBase) {
	lis, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer(
		grpc.KeepaliveParams(keepalive.ServerParameters{
			MaxConnectionIdle:     5 * time.Minute,  // Idle timeout before closing connection
			MaxConnectionAge:      30 * time.Minute, // Max time before connection is closed
			MaxConnectionAgeGrace: 5 * time.Minute,  // Allow grace period before closing
			Time:                  2 * time.Minute,  // Ping the client every 2 minutes
			Timeout:               20 * time.Second, // Wait 20 seconds for ping ack
		}),
		grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
			MinTime:             1 * time.Minute, // Minimum time between pings from clients
			PermitWithoutStream: true,            // Don't allow pings when there are no active RPCs
		}),
		grpc.MaxConcurrentStreams(0),
	)

	pb.RegisterModuleServiceServer(s, &ModuleServiceHandler{
		app: app,
	})

	pb.RegisterFeedServiceServer(s, &FeedServiceHandler{
		app: app,
	})

	pb.RegisterRoomServiceServer(s, &RoomServiceHandler{
		app: app,
	})

	log.Printf("server listening at %v", lis.Addr())
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
