package admin_promotion

import (
	"context"

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

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

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

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

func (l *DeletePromotionLinkLogic) DeletePromotionLink(req *types.DeletePromotionLinkReq) error {
	// 获取当前用户ID
	adminUserId, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
	if getUidErr != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "删除推广链接, 获取用户信息失败, %+v", getUidErr)
	}

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

	// 验证用户权限
	if link.AdminUserId != adminUserId {
		return errors.Wrapf(xerr.NewErrMsg("无权限删除此链接"), "删除推广链接, 无权限删除此链接, %+v", link)
	}

	// 在事务中执行所有删除操作
	err = l.svcCtx.AdminPromotionLinkModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		// 软删除链接
		err = l.svcCtx.AdminPromotionLinkModel.DeleteSoft(l.ctx, session, link)
		if err != nil {
			return errors.Wrapf(err, "删除推广链接, 软删除链接失败, %+v", err)
		}

		// 软删除总统计记录
		totalStats, err := l.svcCtx.AdminPromotionLinkStatsTotalModel.FindOneByLinkId(l.ctx, link.Id)
		if err != nil && !errors.Is(err, model.ErrNotFound) {
			return errors.Wrapf(err, "删除推广链接, 获取总统计记录失败, %+v", err)
		}
		if totalStats != nil {
			err = l.svcCtx.AdminPromotionLinkStatsTotalModel.DeleteSoft(l.ctx, session, totalStats)
			if err != nil {
				return errors.Wrapf(err, "删除推广链接, 软删除总统计记录失败, %+v", err)
			}
		}

		// 软删除历史统计记录
		builder := l.svcCtx.AdminPromotionLinkStatsHistoryModel.SelectBuilder()
		builder = builder.Where("link_id = ?", link.Id)
		historyStats, err := l.svcCtx.AdminPromotionLinkStatsHistoryModel.FindAll(l.ctx, builder, "")
		if err != nil {
			return errors.Wrapf(err, "删除推广链接, 获取历史统计记录失败, %+v", err)
		}
		for _, stat := range historyStats {
			err = l.svcCtx.AdminPromotionLinkStatsHistoryModel.DeleteSoft(l.ctx, session, stat)
			if err != nil {
				return errors.Wrapf(err, "删除推广链接, 软删除历史统计记录失败, %+v", err)
			}
		}

		return nil
	})

	if err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "删除推广链接失败, %+v", err)
	}

	return nil
}
