package mw

import (
	"context"
	"strings"
	"time"

	"route256/loms/internal/infra/grpc/metrics"

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

const UNKNOWN = "unknown"

func WithMetrics(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
	start := time.Now()

	resp, err = handler(ctx, req)

	// "/pkg.Service/Method"
	service, method := parseFullMethod(info.FullMethod)

	code := status.Code(err).String()

	metrics.IncRequestHandlerCount(service, method, code)
	metrics.StoreHandlerRequestDuration(service, method, code, time.Since(start))

	return resp, err
}

func parseFullMethod(full string) (service, method string) {
	if full == "" {
		return UNKNOWN, UNKNOWN
	}
	full = strings.TrimPrefix(full, "/")

	slash := strings.Index(full, "/")
	if slash < 0 {
		return full, UNKNOWN
	}
	return full[:slash], full[slash+1:]
}
