package middleware

import (
	"net/http"

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

const AdminSessionKey = "admin_user"

func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		user := session.Get(AdminSessionKey)
		if user == nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
			return
		}
		c.Set("admin_user", user.(string))
		c.Set("is_admin", true)
		c.Next()
	}
}

func OptionalAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		if user := session.Get(AdminSessionKey); user != nil {
			c.Set("admin_user", user.(string))
			c.Set("is_admin", true)
		} else {
			c.Set("is_admin", false)
		}
		c.Next()
	}
}

func IsAdmin(c *gin.Context) bool {
	v, exists := c.Get("is_admin")
	if !exists {
		return false
	}
	return v.(bool)
}

func CurrentUser(c *gin.Context) string {
	u, _ := c.Get("admin_user")
	if u == nil {
		return ""
	}
	return u.(string)
}
