package mw

import (
	"context"
	"strings"

	"go.opentelemetry.io/otel/codes"
	"google.golang.org/grpc"
	"google.golang.org/grpc/status"

	"route256/loms/internal/infra/tracing"
)

func WithTracing(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
	service, method := splitFullMethod(info.FullMethod)
	ctx, span := tracing.Tracer().Start(ctx, service+"/"+method)
	defer span.End()

	resp, err := handler(ctx, req)

	if err != nil {
		span.RecordError(err)
		span.SetStatus(codes.Error, status.Convert(err).Message())
	} else {
		span.SetStatus(codes.Ok, "OK")
	}

	return resp, err
}

func splitFullMethod(full string) (service, method string) {
	full = strings.TrimPrefix(full, "/")
	if i := strings.Index(full, "/"); i >= 0 {
		return full[:i], full[i+1:]
	}

	return "unknown", full
}
