package app

import (
	"net/http"

	"bindbox-game/internal/code"
	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/pkg/validation"
)

type bindDouyinOrderRequest struct {
	DouyinID string `json:"douyin_id"`
}

type bindDouyinOrderResponse struct {
	DouyinID string `json:"douyin_id"`
}

// BindDouyinOrder 绑定抖音ID
// @Summary 绑定抖音ID
// @Description 输入抖音号（Buyer ID），绑定到当前用户
// @Tags APP端.用户
// @Accept json
// @Produce json
// @Security LoginVerifyToken
// @Param RequestBody body bindDouyinOrderRequest true "请求参数"
// @Success 200 {object} bindDouyinOrderResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/users/douyin/bind [post]
func (h *handler) BindDouyinOrder() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(bindDouyinOrderRequest)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}

		if req.DouyinID == "" {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "抖音号不能为空"))
			return
		}

		currentUserID := int64(ctx.SessionUserInfo().Id)

		// 0. 检查当前用户信息
		currentUser, err := h.readDB.Users.WithContext(ctx.RequestContext()).Where(h.readDB.Users.ID.Eq(currentUserID)).First()
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusInternalServerError, code.ServerError, "获取用户信息失败"))
			return
		}

		// 如果已经绑定了相同的 ID，直接返回成功
		if currentUser.DouyinUserID == req.DouyinID {
			ctx.Payload(&bindDouyinOrderResponse{DouyinID: req.DouyinID})
			return
		}

		// 1. 检查该抖音号是否已被其他本地账号绑定
		existedUser, _ := h.readDB.Users.WithContext(ctx.RequestContext()).Where(h.readDB.Users.DouyinUserID.Eq(req.DouyinID)).First()
		if existedUser != nil && existedUser.ID != currentUserID {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "该抖音号已被其他账号绑定"))
			return
		}

		// 2. 更新本地用户表的 douyin_user_id
		if _, err := h.writeDB.Users.WithContext(ctx.RequestContext()).Where(h.writeDB.Users.ID.Eq(currentUserID)).Updates(map[string]any{
			"douyin_user_id": req.DouyinID,
		}); err != nil {
			ctx.AbortWithError(core.Error(http.StatusInternalServerError, code.ServerError, "更新用户信息失败"))
			return
		}

		ctx.Payload(&bindDouyinOrderResponse{
			DouyinID: req.DouyinID,
		})
	}
}
