package inference

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/service/updater"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"time"
)

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

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

func (l *DeployInstanceListLogic) DeployInstanceList(req *types.DeployInstanceListReq) (resp *types.DeployInstanceListResp, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.PageNum - 1)
	resp = &types.DeployInstanceListResp{}

	var list []*models.AiInferDeployInstance

	tx := l.svcCtx.DbEngin.Raw("select * from ai_infer_deploy_instance").Scan(&list)
	if tx.Error != nil {
		logx.Errorf(tx.Error.Error())
		return nil, tx.Error
	}

	ins := list[0]
	for i := range list {
		last, _ := time.Parse(time.RFC3339, ins.UpdateTime)
		latest, _ := time.Parse(time.RFC3339, list[i].UpdateTime)
		if latest.After(last) {
			ins = list[i]
		}
	}

	go updater.UpdateDeployInstanceStatus(l.svcCtx, ins)

	//count total
	var total int64
	err = tx.Count(&total).Error
	tx.Limit(limit).Offset(offset)

	if err != nil {
		return resp, err
	}

	err = tx.Order("create_time desc").Find(&list).Error
	if err != nil {
		return nil, errors.New(err.Error())
	}
	resp.List = &list
	resp.PageSize = req.PageSize
	resp.PageNum = req.PageNum
	resp.Total = total

	return
}
