// backend/internal/auth.go
package internal

import (
	"errors"
	"net/http"

	"github.com/golang-jwt/jwt/v5"
)

var parseJWT = jwt.ParseWithClaims

// CurrentUser parses the Pegasus session cookie and validates its JWT claims.
func CurrentUser(r *http.Request) (Claims, error) {
	c, err := r.Cookie(CookieName)
	if err != nil {
		return Claims{}, err
	}
	tok, err := parseJWT(c.Value, &Claims{}, func(_ *jwt.Token) (any, error) { return sessionKey, nil })
	if err != nil {
		return Claims{}, err
	}
	if cl, ok := tok.Claims.(*Claims); ok && tok.Valid {
		return *cl, nil
	}
	return Claims{}, errors.New("invalid session")
}
