package requestctx

import (
	"github.com/gin-gonic/gin"
	"github.com/nexuscrm/kernel/pkg/auth"
	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/models"
)

// GetUserFromContext extracts the authenticated user from gin.Context.
func GetUserFromContext(c *gin.Context) *models.UserSession {
	userInterface, exists := c.Get(constants.ContextKeyUser)
	if !exists {
		return nil
	}
	authUser := userInterface.(auth.UserSession)
	return &models.UserSession{
		ID:             authUser.ID,
		Name:           authUser.Name,
		Email:          &authUser.Email,
		ProfileID:      authUser.ProfileId,
		ProfileName:    authUser.ProfileName,
		RoleID:         authUser.RoleId,
		RoleName:       authUser.RoleName,
		ConnectedAppId: authUser.ConnectedAppId,
		Scope:          authUser.Scope,
		GrantType:      authUser.GrantType,
		SessionClass:   authUser.SessionClass,
	}
}

// MustGetUser extracts the authenticated user from the request context.
// Panics if user is nil; only use in routes protected by requireAuth middleware.
func MustGetUser(c *gin.Context) *models.UserSession {
	user := GetUserFromContext(c)
	if user == nil {
		panic("MustGetUser: requireAuth middleware not applied")
	}
	return user
}
