package middlewares

import (
	"net/url"
	"strings"
	"time"

	"quyun/app/models"
	"quyun/pkg/utils"

	"github.com/gofiber/fiber/v3"
	log "github.com/sirupsen/logrus"
)

func (f *Middlewares) Auth(ctx fiber.Ctx) error {
	if strings.HasPrefix(ctx.Path(), "/v1/pay/callback/") {
		return ctx.Next()
	}

	if strings.HasPrefix(ctx.Path(), "/v1/auth/") {
		return ctx.Next()
	}

	if strings.HasPrefix(ctx.Path(), "/v1/admin/") {
		return ctx.Next()
	}

	if f.app.IsDevMode() && false {
		user, err := models.Users.GetByID(ctx.Context(), 1)
		if err != nil {
			return ctx.Send([]byte("User not found"))
		}
		ctx.Locals("user", user)
		return ctx.Next()
	}

	fullUrl := utils.FullURI(ctx)
	u, err := url.Parse(fullUrl)
	if err != nil {
		return err
	}
	query := u.Query()
	query.Set("redirect", fullUrl)
	u.RawQuery = query.Encode()
	u.Path = "/v1/auth/wechat"
	fullUrl = u.String()

	// check cookie exists
	cookie := ctx.Cookies("token")
	log.Infof("cookie: %s", cookie)
	if cookie == "" {
		log.Infof("auth redirect_uri: %s", fullUrl)
		if ctx.XHR() {
			return ctx.SendStatus(fiber.StatusUnauthorized)
		}
		return ctx.Redirect().To(fullUrl)
	}

	jwt, err := f.jwt.Parse(cookie)
	if err != nil {
		// remove cookie
		ctx.ClearCookie("token")
		if ctx.XHR() {
			return ctx.SendStatus(fiber.StatusUnauthorized)
		}
		return ctx.Redirect().To(fullUrl)
	}

	user, err := models.Users.GetByID(ctx.Context(), jwt.UserID)
	if err != nil {
		// remove cookie
		ctx.ClearCookie("token")
		if ctx.XHR() {
			return ctx.SendStatus(fiber.StatusUnauthorized)
		}
		return ctx.Redirect().To(fullUrl)
	}

	// TOKEN 过期
	if user.AuthToken.Data.ExpiresAt.Before(time.Now()) {
		// remove cookie
		ctx.ClearCookie("token")
		if ctx.XHR() {
			return ctx.SendStatus(fiber.StatusUnauthorized)
		}
		return ctx.Redirect().To(fullUrl)
	}

	ctx.Locals("user", user)

	return ctx.Next()
}
