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

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

func (l *DetailResourceSpecLogic) DetailResourceSpec(req *types.IdReq) (resp *types.ResourceSpec, err error) {
	resp = &types.ResourceSpec{}
	db := l.svcCtx.DbEngin.Model(&types.ResourceSpec{}).Table("t_resource_spec")
	err = db.Where("id = ? and deleted_at is null", req.Id).Scan(&resp).Error
	if err != nil {
		return nil, err
	}
	if resp.Id == 0 {
		logx.Errorf("resource spec not found , id:%s not found", req.Id)
		return resp, errors.New("resource spec not found")
	}
	var baseSpecs []types.BaseResourceSpec
	baseDb := l.svcCtx.DbEngin.Model(&types.BaseResourceSpec{}).Table("t_base_resource_spec")
	baseDb = baseDb.Where("t_base_resource_spec.deleted_at is null and t_base_resource_spec.resource_spec_id = ?", resp.Id)
	err = baseDb.Scan(&baseSpecs).Error
	if err != nil {
		return resp, err
	}
	resp.BaseResourceSpecs = baseSpecs
	return
}
