package agent

import (
	"context"
	"bdrp-server/app/main/model"
	"bdrp-server/common/ctxdata"
	"bdrp-server/common/xerr"

	"github.com/pkg/errors"

	"bdrp-server/app/main/api/internal/svc"
	"bdrp-server/app/main/api/internal/types"

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

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

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

func (l *SaveAgentMembershipUserConfigLogic) SaveAgentMembershipUserConfig(req *types.SaveAgentMembershipUserConfigReq) error {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "保存会员代理报告配置，获取用户ID失败: %v", err)
	}
	agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "保存会员代理报告配置: %v", err)
	}

	var agentMembershipUserConfigModel *model.AgentMembershipUserConfig
	agentMembershipUserConfigModel, err = l.svcCtx.AgentMembershipUserConfigModel.FindOneByAgentIdProductId(l.ctx, agentModel.Id, req.ProductID)

	// 检查记录是否存在
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			// 记录不存在，创建新的配置对象
			agentMembershipUserConfigModel = &model.AgentMembershipUserConfig{
				UserId:              userID,
				AgentId:             agentModel.Id,
				ProductId:           req.ProductID,
				PriceRatio:          req.PriceRatio,
				PriceIncreaseAmount: req.PriceIncreaseAmount,
				PriceRangeFrom:      req.PriceRangeFrom,
				PriceRangeTo:        req.PriceRangeTo,
			}

			// 插入新记录
			_, err = l.svcCtx.AgentMembershipUserConfigModel.Insert(l.ctx, nil, agentMembershipUserConfigModel)
			if err != nil {
				return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "保存会员代理报告配置，插入新记录失败: %v", err)
			}
			return nil
		}

		// 其他错误
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "保存会员代理报告配置，查询记录失败: %v", err)
	}

	// 记录存在，更新现有配置
	agentMembershipUserConfigModel.PriceRatio = req.PriceRatio
	agentMembershipUserConfigModel.PriceIncreaseAmount = req.PriceIncreaseAmount
	agentMembershipUserConfigModel.PriceRangeFrom = req.PriceRangeFrom
	agentMembershipUserConfigModel.PriceRangeTo = req.PriceRangeTo

	_, err = l.svcCtx.AgentMembershipUserConfigModel.Update(l.ctx, nil, agentMembershipUserConfigModel)
	if err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "保存会员代理报告配置，更新记录失败: %v", err)
	}

	return nil
}
