package auth

import (
	"net/http"

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

const ctxSession = "admin_session_obj"

func load(c *gin.Context) *Session {
	id, err := c.Cookie(CookieName)
	if err != nil || id == "" {
		return nil
	}
	s, err := Get(c.Request.Context(), id)
	if err != nil {
		return nil
	}
	return s
}

// Current returns the session, or nil.
func Current(c *gin.Context) *Session {
	if v, ok := c.Get(ctxSession); ok {
		if s, ok := v.(*Session); ok {
			return s
		}
	}
	return nil
}

func RequireStaff() gin.HandlerFunc {
	return func(c *gin.Context) {
		s := load(c)
		if s == nil || s.Kind != KindStaff {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "sign in required"})
			return
		}
		c.Set(ctxSession, s)
		c.Next()
	}
}

// RequireCustomer admits both cloud and self-hosted customers. Every handler
// behind it scopes by AccountID via the helper in api/customer.go — never by
// remembering to filter.
func RequireCustomer() gin.HandlerFunc {
	return func(c *gin.Context) {
		s := load(c)
		if s == nil || s.Kind != KindCustomer || s.AccountID == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "sign in required"})
			return
		}
		c.Set(ctxSession, s)
		c.Next()
	}
}
