package admin_feature

import (
	"context"

	"sim-server/app/main/api/internal/svc"
	"sim-server/app/main/api/internal/types"
	"sim-server/common/xerr"

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

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

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

func (l *AdminUpdateFeatureLogic) AdminUpdateFeature(req *types.AdminUpdateFeatureReq) (resp *types.AdminUpdateFeatureResp, err error) {
	// 1. 参数验证
	if req.Id == "" {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.PARAM_VERIFICATION_ERROR),
			"功能ID不能为空, id: %s", req.Id)
	}

	// 2. 查询记录是否存在
	record, err := l.svcCtx.FeatureModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查找功能失败, err: %v, id: %d", err, req.Id)
	}

	// 3. 直接更新record的字段（只更新非空字段）
	if req.ApiId != nil && *req.ApiId != "" {
		record.ApiId = *req.ApiId
	}
	if req.Name != nil && *req.Name != "" {
		record.Name = *req.Name
	}

	// 4. 执行更新操作
	err = l.svcCtx.FeatureModel.UpdateWithVersion(l.ctx, nil, record)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"更新功能失败, err: %v, id: %d", err, req.Id)
	}

	// 5. 返回成功结果
	return &types.AdminUpdateFeatureResp{Success: true}, nil
}
