package tracing

import (
	"context"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/sdk/resource"
	"go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
	oteltrace "go.opentelemetry.io/otel/trace"
)

var (
	globalTracer oteltrace.Tracer
	provider     *trace.TracerProvider
)

func NewTracer(serviceName string, option ...trace.TracerProviderOption) oteltrace.Tracer {
	option = append([]trace.TracerProviderOption{
		trace.WithResource(resource.NewWithAttributes(
			semconv.SchemaURL,
			semconv.ServiceName(serviceName),
		)),
	}, option...)

	provider = trace.NewTracerProvider(option...)

	otel.SetTracerProvider(provider)

	globalTracer = otel.GetTracerProvider().Tracer("cart")

	return globalTracer
}

func Shutdown(ctx context.Context) error {
	if provider != nil {
		return provider.Shutdown(ctx)
	}
	return nil
}

func Tracer() oteltrace.Tracer {
	if globalTracer == nil {
		return otel.Tracer("cart")
	}

	return globalTracer
}
