package admin_product

import (
	"context"
	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"
	"qnc-server/common/xerr"

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

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

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

func (l *AdminDeleteProductLogic) AdminDeleteProduct(req *types.AdminDeleteProductReq) (resp *types.AdminDeleteProductResp, err error) {
	// 1. 查询记录是否存在
	record, err := l.svcCtx.ProductModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查找产品失败, err: %v, id: %d", err, req.Id)
	}

	// 2. 执行软删除（使用事务确保产品表和代理产品配置表同步）
	err = l.svcCtx.ProductModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		// 2.1 软删除产品
		err = l.svcCtx.ProductModel.DeleteSoft(ctx, session, record)
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
				"删除产品失败, err: %v, id: %d", err, req.Id)
		}

		// 2.2 同步软删除代理产品配置
		agentProductConfig, err := l.svcCtx.AgentProductConfigModel.FindOneByProductId(ctx, req.Id)
		if err != nil {
			// 如果代理产品配置不存在，记录日志但不影响主流程
			l.Infof("同步删除代理产品配置失败：代理产品配置不存在, productId: %d, err: %v", req.Id, err)
		} else {
			err = l.svcCtx.AgentProductConfigModel.DeleteSoft(ctx, session, agentProductConfig)
			if err != nil {
				return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
					"同步删除代理产品配置失败, err: %v, productId: %d", err, req.Id)
			}
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	// 3. 返回结果
	return &types.AdminDeleteProductResp{Success: true}, nil
}
