// Code generated by hertz generator.

package core

import (
	"common/utils"
	"context"

	core "gateway/biz/model/douyin/core"
	"gateway/internal/cache"
	"gateway/internal/db"
	"gateway/internal/jwt"
	"gateway/internal/services"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
)

// Register .
// @router /douyin/user/register/ [POST]
func Register(ctx context.Context, c *app.RequestContext) {
	var err error
	var req core.DouyinUserRegisterRequest
	err = c.BindAndValidate(&req)
	if err != nil {
		utils.InvalidInput(c, err)
		return
	}

	user, err := db.CreateUser(req.Username, req.Password)
	if err != nil {
		utils.Error(c, err)
		return
	}
	token, err := jwt.NewAuthorization(user.Id, req.Username)
	if err != nil {
		utils.Error(c, err)
		return
	}

	resp := &core.DouyinUserRegisterResponse{
		UserId: user.Id,
		Token:  token,
	}

	cache.Flush(resp.UserId)

	c.JSON(consts.StatusOK, resp)
}

// Login .
// @router /douyin/user/login/ [POST]
func Login(ctx context.Context, c *app.RequestContext) {
	var err error
	var req core.DouyinUserLoginRequest
	err = c.BindAndValidate(&req)
	if err != nil {
		utils.InvalidInput(c, err)
		return
	}

	user, err := db.FindUserByName(req.Username)
	if err != nil {
		utils.Error(c, err)
		return
	}
	if err := user.VerifyPassword(req.Password); err != nil {
		utils.Error(c, err)
		return
	}
	token, err := jwt.NewAuthorization(user.Id, req.Username)
	if err != nil {
		utils.Error(c, err)
		return
	}

	resp := &core.DouyinUserLoginResponse{
		UserId: user.Id,
		Token:  token,
	}

	c.JSON(consts.StatusOK, resp)
}

// Info .
// @router /douyin/user/ [GET]
func Info(ctx context.Context, c *app.RequestContext) {
	var err error
	var req core.DouyinUserRequest
	err = c.BindAndValidate(&req)
	if err != nil {
		utils.InvalidInput(c, err)
		return
	}

	id, err := jwt.AuthorizedUser(c, &req.Token)
	if err != nil {
		utils.Error(c, err)
		return
	}

	users, err := services.GatherUserInfoFromIds(ctx, id, []int64{req.UserId}, nil, true, true)
	if err != nil {
		utils.ErrorRpcTimeout.Write(c)
		return
	}

	resp := &core.DouyinUserResponse{
		User: users[req.UserId],
	}

	c.JSON(consts.StatusOK, resp)
}
