package admin_promotion

import (
	"context"
	"fmt"

	"ycc-server/app/main/api/internal/svc"
	"ycc-server/app/main/api/internal/types"
	"ycc-server/app/main/model"
	"ycc-server/common/ctxdata"
	"ycc-server/common/xerr"

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

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

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

func (l *GetPromotionLinkDetailLogic) GetPromotionLinkDetail(req *types.GetPromotionLinkDetailReq) (resp *types.GetPromotionLinkDetailResp, err error) {
	// 获取当前用户ID
	adminUserId, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
	if getUidErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取当前用户ID失败, %+v", getUidErr)
	}

	// 获取链接信息
	link, err := l.svcCtx.AdminPromotionLinkModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(err, "获取链接信息失败, %+v", err)
	}

	// 验证用户权限
	if link.AdminUserId != adminUserId {
		return nil, errors.Wrapf(xerr.NewErrMsg("无权限访问此链接"), "获取链接信息失败, 无权限访问此链接, %+v", link)
	}

	// 获取总统计
	totalStats, err := l.svcCtx.AdminPromotionLinkStatsTotalModel.FindOne(l.ctx, link.Id)
	if err != nil && !errors.Is(err, model.ErrNotFound) {
		return nil, errors.Wrapf(err, "获取总统计失败, %+v", err)
	}
	return &types.GetPromotionLinkDetailResp{
		Name:          link.Name,
		Url:           link.Url,
		ClickCount:    totalStats.ClickCount,
		PayCount:      totalStats.PayCount,
		PayAmount:     fmt.Sprintf("%.2f", totalStats.PayAmount),
		CreateTime:    link.CreateTime.Format("2006-01-02 15:04:05"),
		UpdateTime:    link.UpdateTime.Format("2006-01-02 15:04:05"),
		LastClickTime: totalStats.LastClickTime.Time.Format("2006-01-02 15:04:05"),
		LastPayTime:   totalStats.LastPayTime.Time.Format("2006-01-02 15:04:05"),
	}, nil
}
