// Package contextvar add by blacknc <blacknc@163.com> at 2023/09/06 16:27:22
package contextvar

import (
	"context"
	"time"

	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
)

type ctxValueType string

const (
	requestBeginTime ctxValueType = "__REQUEST_BEGIN__"
	zapLogger        ctxValueType = "__ZAP_LOGGER__"
	accountIDKey     ctxValueType = "__ACCOUNT_ID__"
)

// WithRequestBeginTime set request begin time to context
func WithRequestBeginTime(ctx context.Context, tm time.Time) context.Context {
	return context.WithValue(ctx, requestBeginTime, tm)
}

// RequestBeginTime get request begin time from context
func RequestBeginTime(ctx context.Context) time.Time {
	tm, _ := ctx.Value(requestBeginTime).(time.Time)
	return tm
}

// WithLogger set zap logger to context
func WithLogger(ctx context.Context, logger *zap.Logger) context.Context {
	return context.WithValue(ctx, zapLogger, logger)
}
func WithLoggerField(ctx context.Context, fields ...zap.Field) context.Context {
	l := Logger(ctx).With(fields...)
	return WithLogger(ctx, l)
}

// Logger get zap logger from context
func Logger(ctx context.Context) *zap.Logger {
	logger, _ := ctx.Value(zapLogger).(*zap.Logger)
	if logger == nil {
		logger = tilog.WithContextL(ctx)
	}
	return logger
}

// WithAccountID set user account id to context
func WithAccountID(ctx context.Context, accountID string) context.Context {
	return context.WithValue(ctx, accountIDKey, accountID)
}

// AcccountID get user account id from context
func AccountID(ctx context.Context) string {
	accountID, _ := ctx.Value(accountIDKey).(string)
	return accountID
}
