package app

import (
    "net/http"

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

type addAddressRequest 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"`
}

type addAddressResponse struct {
    ID int64 `json:"id"`
}

// AddUserAddress 新增用户地址
// @Summary 新增用户地址
// @Description 为当前登录用户新增收货地址，可选择设为默认
// @Tags APP端.用户
// @Accept json
// @Produce json
// @Param user_id path integer true "用户ID"
// @Security LoginVerifyToken
// @Param RequestBody body addAddressRequest true "请求参数"
// @Success 200 {object} addAddressResponse
// @Failure 400 {object} code.Failure "参数错误"
// @Failure 401 {object} code.Failure "未授权"
// @Failure 500 {object} code.Failure "服务器内部错误"
// @Router /api/app/users/{user_id}/addresses [post]
func (h *handler) AddUserAddress() core.HandlerFunc {
    return func(ctx core.Context) {
        req := new(addAddressRequest)
        rsp := new(addAddressResponse)
        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)
        in := usersvc.AddAddressInput{
            Name:      req.Name,
            Mobile:    req.Mobile,
            Province:  req.Province,
            City:      req.City,
            District:  req.District,
            Address:   req.Address,
            IsDefault: req.IsDefault,
        }
        row, err := h.user.AddAddress(ctx.RequestContext(), userID, in)
        if err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, 10011, err.Error()))
            return
        }
        rsp.ID = row.ID
        ctx.Payload(rsp)
    }
}