package impl

import (
	"context"
	"regexp"

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

var changefeedInstanceTypeNameRegexp = regexp.MustCompile(`^\d+rcu$`)

// MachineManager is used by two scenarios, biz_changefeed and global ticdc cluster orchestration.
// For the global ticdc cluster orchestration, it uses ticdcClusterMachineManager to manage specifications.
// For the biz_changefeed, if it depends on global ticdc cluster orchestration,
// it uses ticdcClusterMachineManager to manage specifications.
// If it depends on regional ticdc cluster orchestration,
// it uses changefeedMachineManagerWrapper to manage specifications.
type machineManagerRouter struct {
	// use the changefeed_instance_types table to manage specifications of biz_changefeed
	changefeedMachineManagerWrapper ticdc.MachineManager
}

func NewMachineManagerRouter(
	instanceTypeModel ticdc_spec.CDCInstanceTypeModel,
) ticdc.MachineManager {
	changefeedWrapper := NewMachineManagerChangefeedWrapperImpl(instanceTypeModel)
	return &machineManagerRouter{
		changefeedMachineManagerWrapper: changefeedWrapper,
	}
}

func (m *machineManagerRouter) Query(
	ctx context.Context, req *domain.QuerySpecificationReq,
) (*domain.QuerySpecificationResp, bizerr.BizError) {
	return m.changefeedMachineManagerWrapper.Query(ctx, req)
}

// ListSpecifications is only used by biz_changefeed. There are two scenarios.
// The one is getting available changefeed specifications for a tidb cluster when create or scale a changefeed.
// The other is getting all the changefeed specifications to meter all the changefeeds,
// and the parameter of InfraProviderType is nil.
func (m *machineManagerRouter) ListSpecifications(
	ctx context.Context, req *domain.ListSpecificationsReq,
) (*domain.ListSpecificationsResp, bizerr.BizError) {
	return m.changefeedMachineManagerWrapper.ListSpecifications(ctx, req)
}
