package auth

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/AgentTeam/desktop/internal/token"
)

// LogoutHandler returns a gin handler that invalidates the current session token.
func LogoutHandler(onLogout ...func(string)) gin.HandlerFunc {
	return func(c *gin.Context) {
		authToken := ""
		if h := c.GetHeader("Authorization"); h != "" {
			if tok, ok := cutPrefix(h, "Bearer "); ok {
				authToken = tok
			}
		}
		if authToken == "" {
			authToken = c.GetHeader("X-Session-Token")
		}
		if authToken != "" {
			token.DeleteSession(authToken)
			for _, notify := range onLogout {
				if notify != nil {
					notify(authToken)
				}
			}
		}
		c.JSON(http.StatusOK, gin.H{"status": "ok"})
	}
}

func cutPrefix(s, prefix string) (after string, found bool) {
	if len(s) >= len(prefix) && s[:len(prefix)] == prefix {
		return s[len(prefix):], true
	}
	return "", false
}
