// backend/internal/session.go
package internal

import (
	"net/http"
	"os"
	"time"

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

type Claims struct {
	Username string `json:"u"`
	JFToken  string `json:"t"`
	jwt.RegisteredClaims
}

var sessionKey = []byte(os.Getenv("PEGASUS_SESSION_KEY"))
var cookieSecure = os.Getenv("PEGASUS_COOKIE_INSECURE") != "1"

const CookieName = "pegasus_session"

func SetSession(w http.ResponseWriter, username, jfToken string) error {
	now := time.Now()
	tok := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{
		Username: username,
		JFToken:  jfToken,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(now.Add(7 * 24 * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(now),
		},
	})
	signed, err := tok.SignedString(sessionKey)
	if err != nil {
		return err
	}
	http.SetCookie(w, &http.Cookie{
		Name:     CookieName,
		Value:    signed,
		Path:     "/",
		HttpOnly: true,
		Secure:   cookieSecure,
		SameSite: http.SameSiteLaxMode,
	})
	return nil
}

func ClearSession(w http.ResponseWriter) {
	http.SetCookie(w, &http.Cookie{
		Name:     CookieName,
		Value:    "",
		Expires:  time.Unix(0, 0),
		MaxAge:   -1,
		Path:     "/",
		HttpOnly: true,
		Secure:   cookieSecure,
		SameSite: http.SameSiteLaxMode,
	})
}
