package greet

import (
	"context"

	"dance-lessons-coach/pkg/user"

	"github.com/rs/zerolog/log"
)

// Context key for storing authenticated user
type contextKey string

const (
	// UserContextKey is the context key for storing authenticated user
	UserContextKey contextKey = "authenticatedUser"
)

type Service struct{}

func NewService() *Service {
	return &Service{}
}

// GetAuthenticatedUserFromContext extracts the authenticated user from context
func GetAuthenticatedUserFromContext(ctx context.Context) (*user.User, bool) {
	user, ok := ctx.Value(UserContextKey).(*user.User)
	return user, ok
}

// Greet returns a greeting message for the given name.
// If name is empty, it checks for authenticated user and uses their username.
// If no authenticated user and no name, it defaults to "world".
// Implements the Greeter interface.
func (s *Service) Greet(ctx context.Context, name string) string {
	log.Trace().Ctx(ctx).Str("name", name).Msg("Greet function called")

	// If no name provided, check for authenticated user
	if name == "" {
		if authenticatedUser, ok := GetAuthenticatedUserFromContext(ctx); ok {
			name = authenticatedUser.Username
			log.Trace().Ctx(ctx).Str("authenticated_user", name).Msg("Using authenticated username for greeting")
		}
	}

	if name == "" {
		return "Hello world!"
	}
	return "Hello " + name + "!"
}
