package adapters

import (
	"context"
	"github.com/pkg/errors"

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

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

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

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

func (l *DeleteAdapterLogic) DeleteAdapter(req *types.AdapterDelReq) (resp *types.AdapterResp, err error) {
	var sId int64
	l.svcCtx.DbEngin.Table("t_adapter").Raw("select a.id from t_cluster c left join t_adapter a on c.adapter_id=a.id where a.id = ? ", req.Id).Scan(&sId)
	if sId != 0 {
		return nil, errors.New("Delete failed,The adapter is associated with a cluster")
	}
	db := l.svcCtx.DbEngin.Table("t_adapter").Where("id = ?", req.Id).First(&types.AdapterInfo{})
	if db.Error != nil {
		logx.Errorf("err %v", db.Error.Error())
		return nil, errors.New("Adapter does not exist")
	}
	tx := l.svcCtx.DbEngin.Table("t_adapter").Delete(types.AdapterInfo{}, req.Id)
	if tx.Error != nil {
		logx.Errorf("err %v", db.Error.Error())
		return nil, errors.New("Delete adapter failed")
	}
	return
}
