package apps

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/types"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
)

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

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

func (l *DeleteAppByAppNameLogic) DeleteAppByAppName(req *types.DeleteAppReq) (resp *types.DeleteAppResp, err error) {
	resp = &types.DeleteAppResp{}
	var task = &Task{}
	//查询应用的yamlString
	l.svcCtx.DbEngin.Raw(`select * from task where ns_id= ? and name= ? AND deleted_at IS NULL`, req.NsID, req.Name).Scan(&task)
	if task.Id == 0 {
		resp.Code = 500
		resp.Msg = "App not fount"
		return resp, err
	}
	//删除主任务信息
	l.svcCtx.DbEngin.Model(&models.Task{}).Where("id", task.Id).Update("status", constants.Deleted)
	tx := l.svcCtx.DbEngin.Delete(&models.Task{}, task.Id)
	if tx.Error != nil {
		return nil, tx.Error
	}
	// 将子任务状态修改为待删除
	tx = l.svcCtx.DbEngin.Model(&models.Cloud{}).Where("task_id", task.Id).Update("status", constants.WaitDelete)
	l.svcCtx.DbEngin.Where("task_id = ?", task.Id).Delete(&models.Cloud{})
	if tx.Error != nil {
		return nil, tx.Error
	}
	return
}
