package app

import (
	"fmt"
	"net/http"
	"time"

	"mini-chat/internal/code"
	"mini-chat/internal/pkg/core"
	"mini-chat/internal/pkg/validation"
	"mini-chat/internal/repository/mysql/model"

	"gorm.io/gorm"
)

type createAppUserRequest struct {
	AppID      string `json:"app_id" binding:"required"`    // 小程序ID
	UserID     string `json:"user_id" binding:"required"`   // 用户ID
	UserName   string `json:"user_name" binding:"required"` // 用户昵称
	UserMobile string `json:"user_mobile"`                  // 用户手机号
	UserAvatar string `json:"user_avatar"`                  // 用户头像
}

type createAppUserResponse struct {
	Message string `json:"message"` // 提示信息
}

// CreateAppUser 新增小程序用户
// @Summary 新增小程序用户
// @Description 新增小程序用户
// @Tags 用户端
// @Accept json
// @Produce json
// @Param RequestBody body createAppUserRequest true "请求参数"
// @Success 200 {object} createAppUserResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/user/create [post]
func (h *handler) CreateAppUser() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(createAppUserRequest)
		res := new(createAppUserResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				validation.Error(err)),
			)
			return
		}

		info, err := h.readDB.AppUser.WithContext(ctx.RequestContext()).
			Where(h.readDB.AppUser.AppID.Eq(req.AppID)).
			Where(h.readDB.AppUser.UserID.Eq(req.UserID)).
			First()
		if err != nil && err != gorm.ErrRecordNotFound {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.CreateAppUserError,
				fmt.Sprintf("%s: %s", code.Text(code.CreateAppUserError), err.Error())),
			)
			return
		}

		if info == nil {
			AppUser := new(model.AppUser)
			AppUser.AppID = req.AppID
			AppUser.UserID = req.UserID
			AppUser.UserName = req.UserName
			AppUser.UserMobile = req.UserMobile
			AppUser.UserAvatar = req.UserAvatar
			AppUser.CreatedAt = time.Now()
			if err := h.writeDB.AppUser.WithContext(ctx.RequestContext()).Create(AppUser); err != nil {
				ctx.AbortWithError(core.Error(
					http.StatusBadRequest,
					code.CreateAppUserError,
					fmt.Sprintf("%s: %s", code.Text(code.CreateAppUserError), err.Error())),
				)
				return
			}
		}

		res.Message = "操作成功"
		ctx.Payload(res)
	}
}
