// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0

package virtualmcpserverstatus

import (
	"context"
	"testing"

	"github.com/stretchr/testify/assert"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1"
)

func TestStatusCollector_SetPhase(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetPhase(mcpv1beta1.VirtualMCPServerPhaseReady)

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Equal(t, mcpv1beta1.VirtualMCPServerPhaseReady, status.Phase)
}

func TestStatusCollector_SetMessage(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetMessage("test message")

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Equal(t, "test message", status.Message)
}

func TestStatusCollector_SetURL(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetURL("http://test.example.com")

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Equal(t, "http://test.example.com", status.URL)
}

func TestStatusCollector_SetObservedGeneration(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetObservedGeneration(42)

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Equal(t, int64(42), status.ObservedGeneration)
}

func TestStatusCollector_SetOIDCConfigHash(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetOIDCConfigHash("abc123hash")

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Equal(t, "abc123hash", status.OIDCConfigHash)
}

func TestStatusCollector_SetOIDCConfigHash_Clear(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetOIDCConfigHash("")

	status := &mcpv1beta1.VirtualMCPServerStatus{OIDCConfigHash: "old-hash"}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Empty(t, status.OIDCConfigHash)
}

func TestStatusCollector_SetGroupRefValidatedCondition(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetGroupRefValidatedCondition("TestReason", "test message", metav1.ConditionTrue)

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Len(t, status.Conditions, 1)
	assert.Equal(t, mcpv1beta1.ConditionTypeVirtualMCPServerGroupRefValidated, status.Conditions[0].Type)
	assert.Equal(t, metav1.ConditionTrue, status.Conditions[0].Status)
	assert.Equal(t, "TestReason", status.Conditions[0].Reason)
	assert.Equal(t, "test message", status.Conditions[0].Message)
}

func TestStatusCollector_SetReadyCondition(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetReadyCondition("DeploymentReady", "deployment is ready", metav1.ConditionTrue)

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Len(t, status.Conditions, 1)
	assert.Equal(t, mcpv1beta1.ConditionTypeVirtualMCPServerReady, status.Conditions[0].Type)
	assert.Equal(t, metav1.ConditionTrue, status.Conditions[0].Status)
	assert.Equal(t, "DeploymentReady", status.Conditions[0].Reason)
	assert.Equal(t, "deployment is ready", status.Conditions[0].Message)
}

func TestStatusCollector_BatchedUpdates(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	// Collect multiple changes
	collector.SetPhase(mcpv1beta1.VirtualMCPServerPhaseReady)
	collector.SetMessage("test message")
	collector.SetURL("http://test.example.com")
	collector.SetObservedGeneration(42)
	collector.SetOIDCConfigHash("oidc-hash-123")
	collector.SetGroupRefValidatedCondition("TestReason", "group is valid", metav1.ConditionTrue)
	collector.SetReadyCondition("DeploymentReady", "deployment is ready", metav1.ConditionTrue)

	// Apply all at once
	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Equal(t, mcpv1beta1.VirtualMCPServerPhaseReady, status.Phase)
	assert.Equal(t, "test message", status.Message)
	assert.Equal(t, "http://test.example.com", status.URL)
	assert.Equal(t, int64(42), status.ObservedGeneration)
	assert.Equal(t, "oidc-hash-123", status.OIDCConfigHash)
	assert.Len(t, status.Conditions, 2)
}

func TestStatusCollector_NoChanges(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	// Don't set any changes
	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.False(t, hasUpdates)
}

func TestStatusCollector_SetAuthConfiguredCondition(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetAuthConfiguredCondition("AuthValid", "auth is configured", metav1.ConditionTrue)

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Len(t, status.Conditions, 1)
	assert.Equal(t, mcpv1beta1.ConditionTypeAuthConfigured, status.Conditions[0].Type)
	assert.Equal(t, metav1.ConditionTrue, status.Conditions[0].Status)
	assert.Equal(t, "AuthValid", status.Conditions[0].Reason)
	assert.Equal(t, "auth is configured", status.Conditions[0].Message)
}

func TestStatusCollector_SetAuthServerConfigValidatedCondition(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetAuthServerConfigValidatedCondition("AuthServerConfigValid", "AuthServerConfig is valid", metav1.ConditionTrue)

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Len(t, status.Conditions, 1)
	assert.Equal(t, mcpv1beta1.ConditionTypeAuthServerConfigValidated, status.Conditions[0].Type)
	assert.Equal(t, metav1.ConditionTrue, status.Conditions[0].Status)
	assert.Equal(t, "AuthServerConfigValid", status.Conditions[0].Reason)
	assert.Equal(t, "AuthServerConfig is valid", status.Conditions[0].Message)
}

func TestStatusCollector_MultipleConditions(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetGroupRefValidatedCondition("GroupValid", "group is valid", metav1.ConditionTrue)
	collector.SetAuthConfiguredCondition("AuthValid", "auth is configured", metav1.ConditionTrue)
	collector.SetReadyCondition("DeploymentReady", "deployment is ready", metav1.ConditionTrue)

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Len(t, status.Conditions, 3)

	// Verify all three conditions are present
	conditionTypes := make(map[string]bool)
	for _, cond := range status.Conditions {
		conditionTypes[cond.Type] = true
	}
	assert.True(t, conditionTypes[mcpv1beta1.ConditionTypeVirtualMCPServerGroupRefValidated])
	assert.True(t, conditionTypes[mcpv1beta1.ConditionTypeAuthConfigured])
	assert.True(t, conditionTypes[mcpv1beta1.ConditionTypeVirtualMCPServerReady])
}

func TestStatusCollector_RemoveConditionsWithPrefix(t *testing.T) {
	t.Parallel()

	// Create a VirtualMCPServer with existing conditions
	vmcp := &mcpv1beta1.VirtualMCPServer{
		Status: mcpv1beta1.VirtualMCPServerStatus{
			Conditions: []metav1.Condition{
				{
					Type:   "DiscoveredAuthConfig-backend-1",
					Status: metav1.ConditionTrue,
					Reason: "ConversionSucceeded",
				},
				{
					Type:   "DiscoveredAuthConfig-backend-2",
					Status: metav1.ConditionTrue,
					Reason: "ConversionSucceeded",
				},
				{
					Type:   "DiscoveredAuthConfig-backend-3",
					Status: metav1.ConditionFalse,
					Reason: "ConversionFailed",
				},
				{
					Type:   "Ready",
					Status: metav1.ConditionTrue,
					Reason: "DeploymentReady",
				},
			},
		},
	}
	collector := NewStatusManager(vmcp)

	// Remove all DiscoveredAuthConfig conditions except backend-1
	collector.RemoveConditionsWithPrefix("DiscoveredAuthConfig-", []string{"DiscoveredAuthConfig-backend-1"})

	// Apply updates
	status := &vmcp.Status
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Len(t, status.Conditions, 2, "Should have 2 conditions remaining: backend-1 and Ready")

	// Verify backend-1 condition remains
	var foundBackend1, foundReady bool
	for _, cond := range status.Conditions {
		if cond.Type == "DiscoveredAuthConfig-backend-1" {
			foundBackend1 = true
		}
		if cond.Type == "Ready" {
			foundReady = true
		}
		// backend-2 and backend-3 should be removed
		assert.NotEqual(t, "DiscoveredAuthConfig-backend-2", cond.Type)
		assert.NotEqual(t, "DiscoveredAuthConfig-backend-3", cond.Type)
	}
	assert.True(t, foundBackend1, "backend-1 condition should remain")
	assert.True(t, foundReady, "Ready condition should remain")
}

func TestStatusCollector_SetTelemetryConfigHash(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetTelemetryConfigHash("tel-hash-456")

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Equal(t, "tel-hash-456", status.TelemetryConfigHash)
}

func TestStatusCollector_SetTelemetryConfigHash_Clear(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetTelemetryConfigHash("")

	status := &mcpv1beta1.VirtualMCPServerStatus{TelemetryConfigHash: "old-hash"}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Empty(t, status.TelemetryConfigHash)
}

func TestStatusCollector_SetTelemetryConfigRefValidatedCondition(t *testing.T) {
	t.Parallel()

	vmcp := &mcpv1beta1.VirtualMCPServer{}
	collector := NewStatusManager(vmcp)

	collector.SetTelemetryConfigRefValidatedCondition(
		"TelemetryConfigRefValid", "MCPTelemetryConfig is valid", metav1.ConditionTrue)

	status := &mcpv1beta1.VirtualMCPServerStatus{}
	hasUpdates := collector.UpdateStatus(context.Background(), status)

	assert.True(t, hasUpdates)
	assert.Len(t, status.Conditions, 1)
	assert.Equal(t, mcpv1beta1.ConditionTypeVirtualMCPServerTelemetryConfigRefValidated, status.Conditions[0].Type)
	assert.Equal(t, metav1.ConditionTrue, status.Conditions[0].Status)
	assert.Equal(t, "TelemetryConfigRefValid", status.Conditions[0].Reason)
	assert.Equal(t, "MCPTelemetryConfig is valid", status.Conditions[0].Message)
}
