package adapters

import (
	"context"
	"github.com/pkg/errors"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
	"gorm.io/gorm"

	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"

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

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

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

func (l *UpdateAdapterLogic) UpdateAdapter(req *types.AdapterReq) (resp *types.AdapterResp, err error) {
	adapter := &types.AdapterInfo{}
	result := l.svcCtx.DbEngin.Table("t_adapter").First(&adapter, req.Id)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("adapter does not exist")
	}
	utils.Convert(req, &adapter)
	l.svcCtx.DbEngin.Table("t_adapter").Model(&adapter).Updates(&adapter)
	return
}
