package middleware

import (
	"net/http"
	"time"
	
	"easydo-echo_win7/utils"
	
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/v4"
)

// AuthMiddleware 认证中间件
func AuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		sess, _ := session.Get("auth_session", c)
		
		// 检查是否已认证
		if auth, ok := sess.Values["is_authenticated"].(bool); !ok || !auth {
			return c.JSON(http.StatusUnauthorized, utils.ErrorResponse("请先登录", ""))
		}
		
		// 检查会话是否过期（超过7天）
		if loginTime, ok := sess.Values["login_time"].(int64); ok {
			if time.Now().Unix()-loginTime > 7*24*60*60 {
				// 清除过期会话
				sess.Options.MaxAge = -1
				sess.Save(c.Request(), c.Response())
				
				return c.JSON(http.StatusUnauthorized, utils.ErrorResponse("会话已过期，请重新登录", ""))
			}
		}
		
		// 将用户信息存入上下文
		c.Set("user_id", sess.Values["user_id"])
		c.Set("username", sess.Values["username"])
		
		return next(c)
	}
}

// AdminMiddleware 管理员中间件
func AdminMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		role := c.Get("role").(string)
		
		if role != "admin" {
			return c.JSON(http.StatusForbidden, utils.ErrorResponse("权限不足", ""))
		}
		
		return next(c)
	}
}