package app

import (
	"net/http"
	"time"

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

type addressShareCreateRequest struct {
	InventoryID      int64  `json:"inventory_id"`
	ExpiresAt        string `json:"expires_at"`
	ExpiresInMinutes int    `json:"expires_in_minutes"`
}

type addressShareCreateResponse struct {
	ShareToken string    `json:"share_token"`
	ShareURL   string    `json:"share_url"`
	ShortLink  string    `json:"short_link"`
	ExpiresAt  time.Time `json:"expires_at"`
}

// CreateAddressShare 创建共享地址链接
// @Summary 创建共享地址链接
// @Description 生成一次性分享令牌（不落库），用于邀请他人填写收货地址；令牌默认有效期1小时（无需传过期参数）
// @Tags APP端.用户
// @Accept json
// @Produce json
// @Param user_id path integer true "用户ID"
// @Security LoginVerifyToken
// @Param RequestBody body addressShareCreateRequest true "请求参数：资产ID（过期参数可不传，默认1小时）"
// @Success 200 {object} addressShareCreateResponse
// @Failure 400 {object} code.Failure "参数错误/资产不可用"
// @Router /api/app/users/{user_id}/inventory/address-share/create [post]
func (h *handler) CreateAddressShare() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(addressShareCreateRequest)
		rsp := new(addressShareCreateResponse)
		if err := ctx.ShouldBindJSON(req); err != nil || req.InventoryID == 0 {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "参数错误"))
			return
		}
		var exp time.Time
		if req.ExpiresInMinutes > 0 {
			exp = time.Now().Add(time.Duration(req.ExpiresInMinutes) * time.Minute)
		} else if req.ExpiresAt != "" {
			if t, err := time.Parse(time.RFC3339, req.ExpiresAt); err == nil {
				exp = t
			} else if mins, err2 := time.ParseDuration(req.ExpiresAt + "m"); err2 == nil {
				exp = time.Now().Add(mins)
			}
		}
		if exp.IsZero() {
			exp = time.Now().Add(60 * time.Minute)
		}
		userID := int64(ctx.SessionUserInfo().Id)
		token, shortLink, exp, err := h.user.CreateAddressShare(ctx.RequestContext(), userID, req.InventoryID, exp)
		if err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 10020, err.Error()))
			return
		}
		rsp.ShareToken = token
		rsp.ShortLink = shortLink
		rsp.ExpiresAt = exp
		rsp.ShareURL = "/api/app/address-share/" + token + "/submit"
		ctx.Payload(rsp)
	}
}
