package impl

import (
	"context"

	"github.com/tidbcloud/dataflow-service/app/models/domain"
	"github.com/tidbcloud/dataflow-service/app/models/ticdc"
	"github.com/tidbcloud/dataflow-service/app/models/ticdc_spec"
	"github.com/tidbcloud/dataflow-service/app/repo/entity"
	"github.com/tidbcloud/pkgv2/bizerr"
)

type machineManagerChangefeedWrapperImpl struct {
	instanceTypeModel ticdc_spec.CDCInstanceTypeModel
}

func NewMachineManagerChangefeedWrapperImpl(instanceTypeModel ticdc_spec.CDCInstanceTypeModel) ticdc.MachineManager {
	return &machineManagerChangefeedWrapperImpl{
		instanceTypeModel: instanceTypeModel,
	}
}

func (m *machineManagerChangefeedWrapperImpl) Query(
	ctx context.Context, req *domain.QuerySpecificationReq,
) (*domain.QuerySpecificationResp, bizerr.BizError) {
	getInsTypeReq := &domain.GetChangefeedInstanceTypeReq{
		Name: req.Code,
	}
	getInsTypeResp, err := m.instanceTypeModel.GetChangefeedInstanceType(ctx, getInsTypeReq)
	if err != nil {
		return nil, err
	}
	return &domain.QuerySpecificationResp{
		Specification: changefeedInstanceType2Specification(getInsTypeResp.InstanceType),
	}, nil
}

func (m *machineManagerChangefeedWrapperImpl) ListSpecifications(
	ctx context.Context, req *domain.ListSpecificationsReq,
) (*domain.ListSpecificationsResp, bizerr.BizError) {
	listInsTypeResp, err := m.instanceTypeModel.ListChangefeedInstanceTypes(ctx)
	if err != nil {
		return nil, err
	}
	specs := make([]*domain.TiCDCClusterSpecification, 0, len(listInsTypeResp.InstanceTypes))
	for _, instanceType := range listInsTypeResp.InstanceTypes {
		specs = append(specs, changefeedInstanceType2Specification(instanceType))
	}
	return &domain.ListSpecificationsResp{
		Specifications: specs,
	}, nil
}

func changefeedInstanceType2Specification(
	instanceType *entity.ChangefeedInstanceType,
) *domain.TiCDCClusterSpecification {
	return &domain.TiCDCClusterSpecification{
		Code:     instanceType.Name,
		RPSLimit: instanceType.RPSLimit,
		RCUNum:   instanceType.RCUNum,
	}
}
