package core

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 CountTaskStatusLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *CountTaskStatusLogic) CountTaskStatus() (resp *types.TaskStatusResp, err error) {
	resp = &types.TaskStatusResp{}
	sqlStr := `SELECT
					COUNT(CASE WHEN status = 'Succeeded' THEN 1 END) AS Succeeded,
					COUNT(CASE WHEN status = 'Failed' THEN 1 END) AS Failed,
					COUNT(CASE WHEN status = 'Running' THEN 1 END) AS Running,
					COUNT(CASE WHEN status = 'Saved' THEN 1 END) AS Saved
				FROM task;`
	err = l.svcCtx.DbEngin.Raw(sqlStr).Scan(&resp).Error
	if err != nil {
		logx.Errorf("CountTaskStatus() => sql execution error: %v", err)
		return nil, errors.Errorf("Description Failed to collect statistics on the status of a task. Please try again later")
	}
	return
}
