package handler

import (
	"gitee.ltd/lxh/wechat-robot/internal/logto"
	"github.com/gofiber/fiber/v2"
	"github.com/valyala/fasthttp/fasthttpadaptor"
	"net/http"
)

// LogtoLogin 重定向到Logto登录页面
func LogtoLogin(c *fiber.Ctx) error {
	// 构建回调URL
	callbackURL := c.Protocol() + "://" + c.Hostname() + "/auth/logto/callback"
	//callbackURL := "https://wechat.0bug.dev/auth/logto/callback"

	// 获取登录链接
	client, err := logto.GetLogtoClient(c)
	if err != nil {
		return c.Redirect("/error?error=Logto登录错误: " + err.Error())
	}
	signInUri, err := client.SignInWithRedirectUri(callbackURL)
	if err != nil {
		return c.Redirect("/error?error=Logto登录错误: " + err.Error() + "。请在Logto控制台确认回调URI为: " + callbackURL)
	}
	// 去登录
	return c.Redirect(signInUri)
}

// LogtoCallback 处理Logto登录回调
func LogtoCallback(c *fiber.Ctx) error {
	client, err := logto.GetLogtoClient(c)
	if err != nil {
		return c.Redirect("/error?error=Logto登录错误: " + err.Error())
	}

	r := &http.Request{}
	if err = fasthttpadaptor.ConvertRequest(c.Context(), r, true); err != nil {
		return c.Redirect("/error?error=转换请求错误: " + err.Error())
	}

	// 处理回调
	if err = client.HandleSignInCallback(r); err != nil {
		return c.Redirect("/error?error=Logto回调处理错误: " + err.Error())
	}

	// 重定向到机器人列表页面
	return c.Redirect("/admin/robots")
}

// LogtoLogout 处理Logto退出登录
func LogtoLogout(c *fiber.Ctx) error {
	client, err := logto.GetLogtoClient(c)
	if err != nil {
		return c.Redirect("/error?error=Logto登录错误: " + err.Error())
	}

	// 构建登出后重定向URL
	postLogoutRedirectURL := c.Protocol() + "://" + c.Hostname()

	// 获取登出链接
	signOutUri, err := client.SignOut(postLogoutRedirectURL)
	if err != nil {
		return c.Redirect("/error?error=Logto登出错误: " + err.Error())
	}

	// 重定向到Logto登出页面
	return c.Redirect(signOutUri)
}
