package app

import (
	"net/http"
	"strconv"

	"bindbox-game/internal/code"
	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/pkg/validation"
	usersvc "bindbox-game/internal/service/user"
)

type updateAddressRequest struct {
	Name      string `json:"name"`
	Mobile    string `json:"mobile"`
	Province  string `json:"province"`
	City      string `json:"city"`
	District  string `json:"district"`
	Address   string `json:"address"`
	IsDefault bool   `json:"is_default"`
}

// UpdateUserAddress 更新用户地址
// @Summary 更新用户地址
// @Description 更新当前登录用户的指定收货地址
// @Tags APP端.用户
// @Accept json
// @Produce json
// @Param user_id path integer true "用户ID"
// @Param address_id path integer true "地址ID"
// @Security LoginVerifyToken
// @Param RequestBody body updateAddressRequest true "请求参数"
// @Success 200 {object} okResponse
// @Failure 400 {object} code.Failure "参数错误"
// @Failure 401 {object} code.Failure "未授权"
// @Failure 500 {object} code.Failure "服务器内部错误"
// @Router /api/app/users/{user_id}/addresses/{address_id} [put]
func (h *handler) UpdateUserAddress() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(updateAddressRequest)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		if req.Name == "" || req.Mobile == "" || req.Province == "" || req.City == "" || req.District == "" || req.Address == "" {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "缺少必要参数"))
			return
		}
		userID := int64(ctx.SessionUserInfo().Id)
		idStr := ctx.Param("address_id")
		addrID, err := strconv.ParseInt(idStr, 10, 64)
		if err != nil || addrID <= 0 {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "地址ID错误"))
			return
		}
		in := usersvc.UpdateAddressInput{
			Name:      req.Name,
			Mobile:    req.Mobile,
			Province:  req.Province,
			City:      req.City,
			District:  req.District,
			Address:   req.Address,
			IsDefault: req.IsDefault,
		}
		if err := h.user.UpdateAddress(ctx.RequestContext(), userID, addrID, in); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10012, err.Error()))
			return
		}
		ctx.Payload(okResponse{Ok: true})
	}
}
