package backup

import (
	"context"

	"github.com/Masterminds/semver/v3"
	"github.com/tidbcloud/core-svc/idl/pbgen/proto/core"
	"github.com/tidbcloud/dataflow-service/app/container"
	"github.com/tidbcloud/dataflow-service/internal/config"
	v1 "github.com/tidbcloud/infra-api/api/v1"
)

func (c BgContext) CanClusterEnableLogBackup(ctx context.Context, tenantID uint64, projectID uint64, clusterID uint64) (bool, error) {
	// check version
	enable, err := c.CanClusterVersionEnableLogBackup(ctx, tenantID, projectID, clusterID)
	if err != nil || !enable {
		return false, err
	}

	// check status
	enable, err = c.CanClusterStatusEnableLogBackup(ctx, tenantID, projectID, clusterID)
	if err != nil || !enable {
		return false, err
	}

	return true, nil
}

func (c BgContext) CanClusterVersionEnableLogBackup(ctx context.Context, tenantID uint64, projectID uint64, clusterID uint64) (bool, error) {
	cluster, bizErr := container.Global().CoreGrpcClient.GetAvailableClusterByID(ctx, clusterID)
	if bizErr != nil {
		c.Log().Sugar().Warnf("get cluster %d failed: %s", clusterID, bizErr.Error())
		return false, nil
	}

	version := cluster.Version
	v, err := semver.NewVersion(version)
	if err != nil {
		c.Log().Sugar().Warnf("parse cluster %d version %s failed: %s", clusterID, version, err.Error())
		return false, nil
	}

	// check tidb version and phase
	if !config.Global().BackupConfig.LogBackupEnableMinVerConstraint.Check(v) {
		c.Log().Sugar().Warnf("log backup enable min version is %s, but cluster %d version is %s", config.Global().BackupConfig.LogBackupEnableMinVer, clusterID, version)
		return false, nil
	}
	return true, nil
}

func (c BgContext) CanClusterStatusEnableLogBackup(ctx context.Context, tenantID uint64, projectID uint64, clusterID uint64) (bool, error) {
	cluster, bizErr := container.Global().CoreGrpcClient.GetAvailableClusterByID(ctx, clusterID)
	if bizErr != nil {
		c.Log().Sugar().Warnf("get cluster %d failed: %s", clusterID, bizErr.Error())
		return false, nil
	}

	clusterStatus := cluster.Status
	// check tidb version and phase
	if clusterStatus != core.ClusterStatus_CLUSTER_STATUS_NORMAL {
		c.Log().Sugar().Warnf("log backup enable cluster status schould be %s, but cluster %d status is %s", v1.ClusterPhaseRunning, clusterID, clusterStatus)
		return false, nil
	}
	return true, nil
}
