package auditlog

import (
	"testing"

	globalcommonv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/common/v1"
	globaldedicatedv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/dedicated/v1"
	"github.com/tidbcloud/tidb-management-service/dedicated-global-service/domain/entity"
	"github.com/tidbcloud/tidb-management-service/utilities/bizerr"
)

// helper to build minimal valid inputs up to the version validation phase
func buildAzureClusterAndConfig(version string) (*entity.Cluster, *globaldedicatedv1.AuditLogConfig) {
	cl := &entity.Cluster{Cluster: &globaldedicatedv1.Cluster{}}
	cl.Version = version
	cl.State = globaldedicatedv1.Cluster_AVAILABLE
	cl.CloudProviderId = globalcommonv1.CloudProvider_AZURE

	cfg := &globaldedicatedv1.AuditLogConfig{
		BucketUrl: "https://account.blob.core.windows.net/container",
	}
	return cl, cfg
}

func TestValidateAuditLogConfig_TiDBVersion(t *testing.T) {
	// invalid semver (missing leading v)
	t.Run("invalid version string", func(t *testing.T) {
		cluster, cfg := buildAzureClusterAndConfig("8.0.0")
		err := ValidateAuditLogConfig(cluster, cfg, V2MinVersion)
		if err == nil {
			t.Fatalf("expected error for invalid version, got nil")
		}
		if err.ErrCode() != bizerr.ErrCodeParams {
			t.Fatalf("expected ErrCodeParams, got %v", err.ErrCode())
		}
	})

	// version lower than min
	t.Run("version lower than min", func(t *testing.T) {
		cluster, cfg := buildAzureClusterAndConfig("v7.0.9")
		err := ValidateAuditLogConfig(cluster, cfg, V2MinVersion)
		if err == nil {
			t.Fatalf("expected error for version lower than min, got nil")
		}
		if err.ErrCode() != bizerr.ErrCodeParams {
			t.Fatalf("expected ErrCodeParams, got %v", err.ErrCode())
		}
	})

	// version equal to min
	t.Run("version equal to min", func(t *testing.T) {
		cluster, cfg := buildAzureClusterAndConfig(V2MinVersion)
		err := ValidateAuditLogConfig(cluster, cfg, V2MinVersion)
		if err != nil {
			t.Fatalf("expected nil error when version == min, got %v", err)
		}
	})

	// version greater than min with rc prerelease
	t.Run("version greater than min rc", func(t *testing.T) {
		cluster, cfg := buildAzureClusterAndConfig("v8.5.4-rc.1")
		err := ValidateAuditLogConfig(cluster, cfg, V2MinVersion)
		if err != nil {
			t.Fatalf("expected nil error for rc version greater than min, got %v", err)
		}
	})
}
