package proxmox

import (
	"context"
	"strings"
	"testing"
)

func TestTenantTagFormat(t *testing.T) {
	tests := []struct {
		name     string
		tenantID string
		want     string
	}{
		{"simple tenant ID", "tenant123", "tenant_tenant123"},
		{"numeric tenant ID", "123", "tenant_123"},
		{"uuid tenant ID", "550e8400-e29b-41d4-a716-446655440000", "tenant_550e8400-e29b-41d4-a716-446655440000"},
		{"tenant with underscore", "tenant_001", "tenant_tenant_001"},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Test tag format generation (as it would be written)
			tag := "tenant_" + tt.tenantID
			if tag != tt.want {
				t.Errorf("Tenant tag format = %q, want %q", tag, tt.want)
			}

			// Verify tag contains tenant ID
			if !strings.Contains(tag, tt.tenantID) {
				t.Errorf("Tenant tag %q does not contain tenant ID %q", tag, tt.tenantID)
			}

			// Verify tag starts with "tenant_"
			if !strings.HasPrefix(tag, "tenant_") {
				t.Errorf("Tenant tag %q does not start with 'tenant_'", tag)
			}
		})
	}
}

func TestTenantTagParsing(t *testing.T) {
	tests := []struct {
		name      string
		tags      string
		tenantID  string
		shouldMatch bool
	}{
		{"single tenant tag", "tenant_123", "123", true},
		{"multiple tags with tenant", "tenant_123,os-ubuntu,env-prod", "123", true},
		{"tenant tag at start", "tenant_123,other-tag", "123", true},
		{"tenant tag at end", "other-tag,tenant_123", "123", true},
		{"tenant tag in middle", "tag1,tenant_123,tag2", "123", true},
		{"wrong tenant ID", "tenant_123", "456", false},
		{"no tenant tag", "os-ubuntu,env-prod", "123", false},
		{"empty tags", "", "123", false},
		{"colon format (old, wrong)", "tenant:123", "123", false}, // Should NOT match colon format
		{"similar but different prefix", "mytenant_123", "123", false},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Simulate tag checking logic as in ListVMs
			tenantTag := "tenant_" + tt.tenantID
			matches := strings.Contains(tt.tags, tenantTag)

			if matches != tt.shouldMatch {
				t.Errorf("Tag matching: tags=%q, tenantID=%q, matches=%v, want %v",
					tt.tags, tt.tenantID, matches, tt.shouldMatch)
			}
		})
	}
}

func TestTenantTagConsistency(t *testing.T) {
	// Verify that write and read formats are consistent
	tenantID := "test-tenant-123"
	
	// Write format (as it would be written in createVM)
	writeTag := "tenant_" + tenantID
	
	// Read format (as it would be checked in ListVMs)
	readTag := "tenant_" + tenantID
	
	if writeTag != readTag {
		t.Errorf("Write tag %q does not match read tag %q", writeTag, readTag)
	}
	
	// Verify they both use underscore
	if !strings.Contains(writeTag, "tenant_") {
		t.Error("Write tag does not use underscore format")
	}
	if !strings.Contains(readTag, "tenant_") {
		t.Error("Read tag does not use underscore format")
	}
	
	// Verify they do NOT use colon (old format)
	if strings.Contains(writeTag, "tenant:") {
		t.Error("Write tag incorrectly uses colon format")
	}
	if strings.Contains(readTag, "tenant:") {
		t.Error("Read tag incorrectly uses colon format")
	}
}

func TestTenantTagWithVMList(t *testing.T) {
	// Test scenario: multiple VMs with different tenant tags
	vmTags := []struct {
		vmID     int
		tags     string
		tenantID string
	}{
		{100, "tenant_123,os-ubuntu", "123"},
		{101, "tenant_456,os-debian", "456"},
		{102, "tenant_123,os-centos", "123"},
		{103, "os-fedora", ""}, // No tenant tag
	}

	// Filter for tenant 123
	filterTenantID := "123"
	tenantTag := "tenant_" + filterTenantID
	
	var filteredVMs []int
	for _, vm := range vmTags {
		if vm.tags != "" && strings.Contains(vm.tags, tenantTag) {
			filteredVMs = append(filteredVMs, vm.vmID)
		}
	}
	
	// Should only get VMs 100 and 102
	expectedVMs := []int{100, 102}
	if len(filteredVMs) != len(expectedVMs) {
		t.Errorf("Filtered VMs count = %d, want %d", len(filteredVMs), len(expectedVMs))
	}
	
	for i, expectedVMID := range expectedVMs {
		if filteredVMs[i] != expectedVMID {
			t.Errorf("Filtered VM[%d] = %d, want %d", i, filteredVMs[i], expectedVMID)
		}
	}
}

// TestTenantTagFormatInVMSpec tests the tenant tag format when creating a VM spec
func TestTenantTagFormatInVMSpec(t *testing.T) {
	ctx := context.Background()
	
	// This test verifies the format would be correct if we had a real client
	// Since we can't easily mock the full client creation, we test the format logic
	tenantID := "test-tenant"
	
	// Simulate the tag format as it would be set in createVM
	vmConfig := make(map[string]interface{})
	vmConfig["tags"] = "tenant_" + tenantID
	
	// Verify format
	if tags, ok := vmConfig["tags"].(string); ok {
		if tags != "tenant_"+tenantID {
			t.Errorf("VM config tags = %q, want %q", tags, "tenant_"+tenantID)
		}
		
		// Verify it uses underscore, not colon
		if strings.Contains(tags, "tenant:") {
			t.Error("Tags incorrectly use colon format")
		}
		if !strings.Contains(tags, "tenant_") {
			t.Error("Tags do not use underscore format")
		}
	} else {
		t.Error("Failed to get tags from VM config")
	}
	
	_ = ctx // Suppress unused variable warning
}

