package query

import (
	"context"
	"encoding/hex"
	"encoding/json"
	"time"

	"tyc-server/app/main/api/internal/svc"
	"tyc-server/app/main/api/internal/types"
	"tyc-server/app/main/model"
	"tyc-server/common/ctxdata"
	"tyc-server/common/xerr"
	"tyc-server/pkg/lzkit/crypto"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type QueryGenerateShareLinkLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewQueryGenerateShareLinkLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryGenerateShareLinkLogic {
	return &QueryGenerateShareLinkLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryGenerateShareLinkLogic) QueryGenerateShareLink(req *types.QueryGenerateShareLinkReq) (resp *types.QueryGenerateShareLinkResp, err error) {
	userId, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取用户ID失败: %v", err)
	}

	// 检查参数
	if (req.OrderId == nil || *req.OrderId == 0) && (req.OrderNo == nil || *req.OrderNo == "") {
		return nil, errors.Wrapf(xerr.NewErrMsg("订单ID和订单号不能同时为空"), "")
	}

	var order *model.Order
	// 优先使用OrderId查询
	if req.OrderId != nil && *req.OrderId != 0 {
		order, err = l.svcCtx.OrderModel.FindOne(l.ctx, *req.OrderId)
		if err != nil {
			if errors.Is(err, model.ErrNotFound) {
				return nil, errors.Wrapf(xerr.NewErrMsg("订单不存在"), "")
			}
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取订单失败: %v", err)
		}
	} else if req.OrderNo != nil && *req.OrderNo != "" {
		// 使用OrderNo查询
		order, err = l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, *req.OrderNo)
		if err != nil {
			if errors.Is(err, model.ErrNotFound) {
				return nil, errors.Wrapf(xerr.NewErrMsg("订单不存在"), "")
			}
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取订单失败: %v", err)
		}
	} else {
		return nil, errors.Wrapf(xerr.NewErrMsg("订单ID和订单号不能同时为空"), "")
	}

	if order.Status != model.OrderStatusPaid {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 订单未支付")
	}

	query, err := l.svcCtx.QueryModel.FindOneByOrderId(l.ctx, order.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取查询失败: %v", err)
	}

	if query.QueryState != model.QueryStateSuccess {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 查询未成功")
	}
	user, err := l.svcCtx.UserModel.FindOne(l.ctx, userId)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 获取用户失败: %v", err)
	}
	if user.Inside != 1 {
		if order.UserId != userId {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 无权操作此订单")
		}
	}

	expireAt := time.Now().Add(time.Duration(l.svcCtx.Config.Query.ShareLinkExpire) * time.Second)
	payload := types.QueryShareLinkPayload{
		OrderId:  order.Id, // 使用查询到的订单ID
		ExpireAt: expireAt.Unix(),
	}
	secretKey := l.svcCtx.Config.Encrypt.SecretKey
	key, err := hex.DecodeString(secretKey)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 解密失败: %v", err)
	}
	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 序列化失败: %v", err)
	}
	encryptedPayload, err := crypto.AesEncryptURL(payloadBytes, key)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成分享链接, 加密失败: %v", err)
	}
	return &types.QueryGenerateShareLinkResp{
		ShareLink: encryptedPayload,
	}, nil
}
