package apps

import (
	"ai-gateway/common/constant"
	"ai-gateway/common/dto"
	"ai-gateway/common/utils"
	"ai-gateway/infrastructure/repository"
	"ai-gateway/service"
	"context"
	"github.com/labstack/echo/v4"
	"net/http"
)

func InitUserGroup(g *echo.Group) {

	//注册
	g.POST("register", func(c echo.Context) error {
		req := new(dto.ThirdRegisterReq)
		if err := c.Bind(req); err != nil {
			return c.JSON(http.StatusOK, utils.Error(err))
		}

		ctx := context.WithValue(context.Background(), constant.DBKey, repository.Db)

		err := service.Login.Register(ctx, *req)
		if err != nil {
			return c.JSON(http.StatusOK, utils.Error(err))
		}

		//登录
		token, _ := service.Login.Login(ctx, dto.ThirdLoginReq{
			Account:  req.Account,
			Password: req.Password,
		})

		return c.JSON(http.StatusOK, utils.Ok(token))
	})

	//登录
	g.POST("login", func(c echo.Context) error {
		req := new(dto.ThirdLoginReq)
		if err := c.Bind(req); err != nil {
			return c.JSON(http.StatusOK, utils.Error(err))
		}

		ctx := context.WithValue(context.Background(), constant.DBKey, repository.Db)

		token, err := service.Login.Login(ctx, *req)
		if err != nil {
			return c.JSON(http.StatusOK, utils.Error(err))
		}

		return c.JSON(http.StatusOK, utils.Ok(token))
	})

	//发送 重置密码 验证码
	g.POST("sendResetPwdCode", func(c echo.Context) error {
		req := new(dto.SendResetPwdCodeReq)
		if err := c.Bind(req); err != nil {
			return c.JSON(http.StatusOK, utils.Error(err))
		}

		err := service.Login.SendResetPwdCode(context.Background(), req.Account)
		if err != nil {
			return c.JSON(http.StatusOK, utils.Error(err))
		}

		return c.JSON(http.StatusOK, utils.Ok(true))
	})

	//重置密码
	g.POST("resetPwd", func(c echo.Context) error {
		req := new(dto.ThirdResetPwdReq)
		if err := c.Bind(req); err != nil {
			return c.JSON(http.StatusOK, utils.Error(err))
		}

		ctx := context.WithValue(context.Background(), constant.DBKey, repository.Db)

		err := service.Login.ResetPwd(ctx, *req)
		if err != nil {
			return c.JSON(http.StatusOK, utils.Error(err))
		}

		return c.JSON(http.StatusOK, utils.Ok(true))
	})

	//根据 token 获取 登录信息
	g.POST("findLoginResult", func(c echo.Context) error {
		ctx := context.WithValue(context.Background(), constant.DBKey, repository.Db)
		loginResult := service.Login.GetLoginResult(ctx, &c)
		return c.JSON(http.StatusOK, utils.Ok(loginResult))
	})
}