package auth

import (
	"context"

	"github.com/gin-gonic/gin"
)

type contextKey string

const principalContextKey contextKey = "acp_principal"

// WithPrincipal attaches verified principal to a standard context.
func WithPrincipal(ctx context.Context, p *Principal) context.Context {
	return context.WithValue(ctx, principalContextKey, p)
}

// PrincipalFromContext reads principal from context (nil if absent).
func PrincipalFromContext(ctx context.Context) *Principal {
	v := ctx.Value(principalContextKey)
	if v == nil {
		return nil
	}
	p, _ := v.(*Principal)
	return p
}

// SetGinPrincipal stores principal on the Gin context.
func SetGinPrincipal(c *gin.Context, p *Principal) {
	c.Set(string(principalContextKey), p)
}

// PrincipalFromGin reads principal from Gin context.
func PrincipalFromGin(c *gin.Context) *Principal {
	v, ok := c.Get(string(principalContextKey))
	if !ok || v == nil {
		return nil
	}
	p, _ := v.(*Principal)
	return p
}
