package apps

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

func InitUserGroup(g *echo.Group) {

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

		ctx := context.WithValue(context.Background(), constant.DBKey, repository.Db)
		platform := utils.GetPlatform(&c)
		req.Platform = platform

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

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

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

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

		ctx := context.WithValue(context.Background(), constant.DBKey, repository.Db)
		//设置platform
		req.Platform = utils.GetPlatform(&c)
		token, err := service.UserBiz.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.UserBiz.SendResetPwdCode(context.Background(), req.Email)
		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.ResetPwdReq)
		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.UserBiz.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, err := service.UserBiz.GetLoginResult(ctx, &c)
		if err != nil {
			return c.JSON(http.StatusOK, utils.Error(err))
		}
		return c.JSON(http.StatusOK, utils.Ok(loginResult))
	})
}