// Copyright (c) 2026 Tigera, Inc. All rights reserved.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package vmipam

import (
	"context"
	"errors"
	"fmt"
	"net"
	"slices"
	"strings"
	"testing"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	v3 "github.com/projectcalico/api/pkg/apis/projectcalico/v3"
	"k8s.io/apimachinery/pkg/util/validation"
	"k8s.io/client-go/kubernetes"

	"github.com/projectcalico/calico/libcalico-go/lib/apiconfig"
	"github.com/projectcalico/calico/libcalico-go/lib/backend"
	bapi "github.com/projectcalico/calico/libcalico-go/lib/backend/api"
	"github.com/projectcalico/calico/libcalico-go/lib/backend/k8s"
	"github.com/projectcalico/calico/libcalico-go/lib/ipam"
	"github.com/projectcalico/calico/libcalico-go/lib/ipam/ipamtestutils"
	cnet "github.com/projectcalico/calico/libcalico-go/lib/net"
	"github.com/projectcalico/calico/libcalico-go/lib/testutils"
)

func TestVMIPAM(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "VM IPAM Suite")
}

var _ = Describe("CreateVMHandleID", func() {
	longName := strings.Repeat("v", 120)

	It("should keep a handle that fits within the limit readable", func() {
		Expect(CreateVMHandleID("", "test-ns", "test-vm")).To(Equal("k8s-pod-network.vmi.test-ns.test-vm"))
	})

	It("should hash a long namespace and name into a valid CRD name", func() {
		handle := CreateVMHandleID("", "test-ns", longName)
		Expect(len(handle)).To(BeNumerically("<=", 128))
		Expect(validation.IsDNS1123Subdomain(handle)).To(BeEmpty())
	})

	It("should give different long names different handles and the same name the same handle", func() {
		handle := CreateVMHandleID("", "test-ns", longName)
		Expect(CreateVMHandleID("", "test-ns", longName)).To(Equal(handle))
		Expect(CreateVMHandleID("", "test-ns", longName+"x")).NotTo(Equal(handle))
		Expect(CreateVMHandleID("", "other-ns", longName)).NotTo(Equal(handle))
	})
})

var _ = Describe("VMHandleNetworks", func() {
	It("should yield the network a handle was built from", func() {
		Expect(slices.Collect(VMHandleNetworks(CreateVMHandleID("net1", "ns", "vm1")))).To(Equal([]string{"net1"}))
	})

	It("should yield the network of a hashed handle", func() {
		handle := CreateVMHandleID("net1", "ns", strings.Repeat("v", 120))
		Expect(slices.Collect(VMHandleNetworks(handle))).To(Equal([]string{"net1"}))
	})

	It("should yield every prefix when the network name contains the infix", func() {
		handle := CreateVMHandleID("a.vmi.b", "ns", "vm1")
		Expect(slices.Collect(VMHandleNetworks(handle))).To(Equal([]string{"a", "a.vmi.b"}))
	})

	It("should yield nothing for a pod handle", func() {
		Expect(slices.Collect(VMHandleNetworks("k8s-pod-network.0123456789abcdef"))).To(BeEmpty())
	})
})

var _ = testutils.E2eDatastoreDescribe("VM IPAM tests", testutils.DatastoreAll, func(config apiconfig.CalicoAPIConfig) {
	var bc bapi.Client
	var ic ipam.Interface
	var kc kubernetes.Interface
	var ipPools *ipamtestutils.IPPoolAccessor

	BeforeEach(func() {
		var err error
		config.Spec.K8sClientQPS = 500
		bc, err = backend.NewClient(config)
		Expect(err).NotTo(HaveOccurred())
		ipPools = &ipamtestutils.IPPoolAccessor{Pools: map[string]ipamtestutils.Pool{}}
		ic = ipam.NewIPAMClient(bc, ipPools, &ipamtestutils.FakeReservations{})

		if config.Spec.DatastoreType == "kubernetes" {
			kc = bc.(*k8s.KubeClient).ClientSet
		}
	})

	Context("CreateVMHandleID", func() {
		It("should hash a long namespace and name into a handle the datastore accepts", func() {
			handle := CreateVMHandleID("", "test-ns", strings.Repeat("v", 120))

			Expect(bc.Clean()).To(Succeed())
			ipPools.Pools = map[string]ipamtestutils.Pool{"10.0.0.0/24": {Enabled: true}}
			ipamtestutils.ApplyNode(bc, kc, "test-host-long", nil)

			v4ia, _, err := ic.AutoAssign(context.Background(), ipam.AutoAssignArgs{
				Num4:        1,
				HandleID:    &handle,
				Hostname:    "test-host-long",
				IntendedUse: v3.IPPoolAllowedUseWorkload,
			})
			Expect(err).NotTo(HaveOccurred())
			Expect(v4ia.IPs).To(HaveLen(1))

			ips, err := ic.IPsByHandle(context.Background(), handle)
			Expect(err).NotTo(HaveOccurred())
			Expect(ips).To(HaveLen(1))
		})
	})

	Context("EnsureActiveVMOwnerAttrs", func() {
		var hostname string
		var handle string
		var allocatedIPs []cnet.IP

		BeforeEach(func() {
			hostname = "test-host-swap"
			handle = "k8s-pod-network.vmi.test-ns.test-vm"

			Expect(bc.Clean()).To(Succeed())
			ipPools.Pools = map[string]ipamtestutils.Pool{}
			ipPools.Pools["10.0.0.0/24"] = ipamtestutils.Pool{Enabled: true}
			ipPools.Pools["fd80:24e2:f998:72d6::/120"] = ipamtestutils.Pool{Enabled: true}
			ipamtestutils.ApplyNode(bc, kc, hostname, nil)

			ctx := context.Background()

			// Allocate dual-stack IPs for the VMI handle
			v4ia, v6ia, err := ic.AutoAssign(ctx, ipam.AutoAssignArgs{
				Num4:        1,
				Num6:        1,
				HandleID:    &handle,
				Hostname:    hostname,
				IntendedUse: v3.IPPoolAllowedUseWorkload,
			})
			Expect(err).NotTo(HaveOccurred())
			Expect(v4ia.IPs).To(HaveLen(1))
			Expect(v6ia.IPs).To(HaveLen(1))

			allocatedIPs = []cnet.IP{
				{IP: v4ia.IPs[0].IP},
				{IP: v6ia.IPs[0].IP},
			}

			// Set source pod as active owner and target pod as alternate owner on all IPs
			for _, ip := range allocatedIPs {
				err := ic.SetOwnerAttributes(ctx, ip, handle, &ipam.OwnerAttributeUpdates{
					ActiveOwnerAttrs: map[string]string{
						ipam.AttributePod:       "virt-launcher-source",
						ipam.AttributeNamespace: "test-ns",
						ipam.AttributeVMIName:   "test-vm",
					},
					AlternateOwnerAttrs: map[string]string{
						ipam.AttributePod:       "virt-launcher-target",
						ipam.AttributeNamespace: "test-ns",
						ipam.AttributeVMIName:   "test-vm",
					},
				}, nil)
				Expect(err).NotTo(HaveOccurred())
			}
		})

		It("should promote target to active owner on all IPs", func() {
			ctx := context.Background()

			err := EnsureActiveVMOwnerAttrs(ctx, ic, allocatedIPs, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())

			for _, ip := range allocatedIPs {
				allocAttr, err := ic.GetAssignmentAttributes(ctx, ip)
				Expect(err).NotTo(HaveOccurred())
				Expect(allocAttr.ActiveOwnerAttrs[ipam.AttributePod]).To(Equal("virt-launcher-target"))
				Expect(allocAttr.ActiveOwnerAttrs[ipam.AttributeNamespace]).To(Equal("test-ns"))
				// Source moves to alternate
				Expect(allocAttr.AlternateOwnerAttrs[ipam.AttributePod]).To(Equal("virt-launcher-source"))
				Expect(allocAttr.AlternateOwnerAttrs[ipam.AttributeNamespace]).To(Equal("test-ns"))
			}
		})

		It("should be idempotent - second call succeeds when target is already active", func() {
			ctx := context.Background()

			err := EnsureActiveVMOwnerAttrs(ctx, ic, allocatedIPs, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())

			// Call again - should succeed (idempotent)
			err = EnsureActiveVMOwnerAttrs(ctx, ic, allocatedIPs, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())

			for _, ip := range allocatedIPs {
				allocAttr, err := ic.GetAssignmentAttributes(ctx, ip)
				Expect(err).NotTo(HaveOccurred())
				Expect(allocAttr.ActiveOwnerAttrs[ipam.AttributePod]).To(Equal("virt-launcher-target"))
			}
		})

		It("should leave the allocation unchanged when alternate is cleared before swap", func() {
			ctx := context.Background()

			// Clear alternate owner on all IPs (simulates target pod deleted before swap)
			for _, ip := range allocatedIPs {
				err := ic.SetOwnerAttributes(ctx, ip, handle, &ipam.OwnerAttributeUpdates{
					ClearAlternateOwner: true,
				}, nil)
				Expect(err).NotTo(HaveOccurred())
			}

			err := EnsureActiveVMOwnerAttrs(ctx, ic, allocatedIPs, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())
			for _, ip := range allocatedIPs {
				allocAttr, err := ic.GetAssignmentAttributes(ctx, ip)
				Expect(err).NotTo(HaveOccurred())
				Expect(allocAttr.ActiveOwnerAttrs[ipam.AttributePod]).To(Equal("virt-launcher-source"))
			}
		})

		It("should return ErrAlternateOwnerMismatch when alternate is a different pod", func() {
			ctx := context.Background()

			// Overwrite alternate with a different pod
			for _, ip := range allocatedIPs {
				err := ic.SetOwnerAttributes(ctx, ip, handle, &ipam.OwnerAttributeUpdates{
					AlternateOwnerAttrs: map[string]string{
						ipam.AttributePod:       "virt-launcher-unexpected",
						ipam.AttributeNamespace: "test-ns",
						ipam.AttributeVMIName:   "test-vm",
					},
				}, nil)
				Expect(err).NotTo(HaveOccurred())
			}

			err := EnsureActiveVMOwnerAttrs(ctx, ic, allocatedIPs, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).To(HaveOccurred())
			Expect(errors.Is(err, ErrAlternateOwnerMismatch)).To(BeTrue(),
				fmt.Sprintf("Expected ErrAlternateOwnerMismatch, got: %v", err))
		})

		It("should skip IPs that are no longer allocated", func() {
			ctx := context.Background()

			// Release all IPs
			err := ic.ReleaseByHandle(ctx, handle)
			Expect(err).NotTo(HaveOccurred())

			err = EnsureActiveVMOwnerAttrs(ctx, ic, allocatedIPs, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())
		})

		It("should skip an IP that is not in any pool", func() {
			ctx := context.Background()
			noPoolIP := cnet.IP{IP: net.ParseIP("192.168.99.1").To4()}

			err := EnsureActiveVMOwnerAttrs(ctx, ic, []cnet.IP{noPoolIP}, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())

			err = EnsureActiveVMOwnerAttrs(ctx, ic, append([]cnet.IP{noPoolIP}, allocatedIPs...), "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())
		})

		It("should succeed with no IPs", func() {
			err := EnsureActiveVMOwnerAttrs(context.Background(), ic, nil, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())
		})

		It("should trust owner attributes naming the VMI when the handle does not match", func() {
			ctx := context.Background()

			// A handle no reconstruction can produce for this VMI, with owner
			// attributes that name it.
			oddHandle := "renamed-nad.vmi.other-ns.other-vm"
			v4ia, _, err := ic.AutoAssign(ctx, ipam.AutoAssignArgs{
				Num4:        1,
				HandleID:    &oddHandle,
				Hostname:    hostname,
				IntendedUse: v3.IPPoolAllowedUseWorkload,
			})
			Expect(err).NotTo(HaveOccurred())
			oddIP := cnet.IP{IP: v4ia.IPs[0].IP}

			err = ic.SetOwnerAttributes(ctx, oddIP, oddHandle, &ipam.OwnerAttributeUpdates{
				ActiveOwnerAttrs: map[string]string{
					ipam.AttributePod:       "virt-launcher-source",
					ipam.AttributeNamespace: "test-ns",
					ipam.AttributeVMIName:   "test-vm",
				},
				AlternateOwnerAttrs: map[string]string{
					ipam.AttributePod:       "virt-launcher-target",
					ipam.AttributeNamespace: "test-ns",
					ipam.AttributeVMIName:   "test-vm",
				},
			}, nil)
			Expect(err).NotTo(HaveOccurred())

			err = EnsureActiveVMOwnerAttrs(ctx, ic, []cnet.IP{oddIP}, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())

			allocAttr, err := ic.GetAssignmentAttributes(ctx, oddIP)
			Expect(err).NotTo(HaveOccurred())
			Expect(allocAttr.ActiveOwnerAttrs[ipam.AttributePod]).To(Equal("virt-launcher-target"))
		})

		It("should skip an IP that is not the VMI's, leaving it untouched", func() {
			ctx := context.Background()

			// Allocate an IP under a pod (container ID) handle.
			podHandle := "k8s-pod-network.0123456789abcdef"
			v4ia, _, err := ic.AutoAssign(ctx, ipam.AutoAssignArgs{
				Num4:        1,
				HandleID:    &podHandle,
				Hostname:    hostname,
				IntendedUse: v3.IPPoolAllowedUseWorkload,
			})
			Expect(err).NotTo(HaveOccurred())
			podIP := cnet.IP{IP: v4ia.IPs[0].IP}

			err = EnsureActiveVMOwnerAttrs(ctx, ic, []cnet.IP{podIP}, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())

			allocAttr, err := ic.GetAssignmentAttributes(ctx, podIP)
			Expect(err).NotTo(HaveOccurred())
			Expect(allocAttr.ActiveOwnerAttrs).To(BeEmpty())
			Expect(allocAttr.AlternateOwnerAttrs).To(BeEmpty())

			err = EnsureActiveVMOwnerAttrs(ctx, ic, append([]cnet.IP{podIP}, allocatedIPs...), "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())
			for _, ip := range allocatedIPs {
				allocAttr, err := ic.GetAssignmentAttributes(ctx, ip)
				Expect(err).NotTo(HaveOccurred())
				Expect(allocAttr.ActiveOwnerAttrs[ipam.AttributePod]).To(Equal("virt-launcher-target"))
			}
		})

		It("should succeed when source was already deleted but target is in alternate", func() {
			ctx := context.Background()

			// Clear active owner (simulates source pod deleted and its attrs cleared)
			for _, ip := range allocatedIPs {
				err := ic.SetOwnerAttributes(ctx, ip, handle, &ipam.OwnerAttributeUpdates{
					ClearActiveOwner: true,
				}, nil)
				Expect(err).NotTo(HaveOccurred())
			}

			// Swap should still succeed - it only verifies alternate
			err := EnsureActiveVMOwnerAttrs(ctx, ic, allocatedIPs, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())

			for _, ip := range allocatedIPs {
				allocAttr, err := ic.GetAssignmentAttributes(ctx, ip)
				Expect(err).NotTo(HaveOccurred())
				Expect(allocAttr.ActiveOwnerAttrs[ipam.AttributePod]).To(Equal("virt-launcher-target"))
				// Active was empty, so alternate should now be empty (nil map swapped in)
				Expect(allocAttr.AlternateOwnerAttrs).To(BeNil())
			}
		})

		It("should work with custom network name", func() {
			ctx := context.Background()

			// Allocate IPs with a custom network handle
			customHandle := "multus-net1.vmi.test-ns.test-vm"
			v4ia, _, err := ic.AutoAssign(ctx, ipam.AutoAssignArgs{
				Num4:        1,
				HandleID:    &customHandle,
				Hostname:    hostname,
				IntendedUse: v3.IPPoolAllowedUseWorkload,
			})
			Expect(err).NotTo(HaveOccurred())
			customIP := cnet.IP{IP: v4ia.IPs[0].IP}

			// Set owners
			err = ic.SetOwnerAttributes(ctx, customIP, customHandle, &ipam.OwnerAttributeUpdates{
				ActiveOwnerAttrs: map[string]string{
					ipam.AttributePod:       "virt-launcher-source",
					ipam.AttributeNamespace: "test-ns",
					ipam.AttributeVMIName:   "test-vm",
				},
				AlternateOwnerAttrs: map[string]string{
					ipam.AttributePod:       "virt-launcher-target",
					ipam.AttributeNamespace: "test-ns",
					ipam.AttributeVMIName:   "test-vm",
				},
			}, nil)
			Expect(err).NotTo(HaveOccurred())

			err = EnsureActiveVMOwnerAttrs(ctx, ic, []cnet.IP{customIP}, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())

			allocAttr, err := ic.GetAssignmentAttributes(ctx, customIP)
			Expect(err).NotTo(HaveOccurred())
			Expect(allocAttr.ActiveOwnerAttrs[ipam.AttributePod]).To(Equal("virt-launcher-target"))
		})

		It("should handle partial success - already-swapped IPs are skipped on retry", func() {
			ctx := context.Background()

			// Manually swap only the first IP
			firstIP := allocatedIPs[0]
			err := ic.SetOwnerAttributes(ctx, firstIP, handle, &ipam.OwnerAttributeUpdates{
				ActiveOwnerAttrs: map[string]string{
					ipam.AttributePod:       "virt-launcher-target",
					ipam.AttributeNamespace: "test-ns",
					ipam.AttributeVMIName:   "test-vm",
				},
				AlternateOwnerAttrs: map[string]string{
					ipam.AttributePod:       "virt-launcher-source",
					ipam.AttributeNamespace: "test-ns",
					ipam.AttributeVMIName:   "test-vm",
				},
			}, nil)
			Expect(err).NotTo(HaveOccurred())

			// Now call the function - first IP should be skipped, second IP should be swapped
			err = EnsureActiveVMOwnerAttrs(ctx, ic, allocatedIPs, "test-ns", "test-vm", "virt-launcher-target")
			Expect(err).NotTo(HaveOccurred())

			// Both IPs should now have target as active
			for _, ip := range allocatedIPs {
				allocAttr, err := ic.GetAssignmentAttributes(ctx, ip)
				Expect(err).NotTo(HaveOccurred())
				Expect(allocAttr.ActiveOwnerAttrs[ipam.AttributePod]).To(Equal("virt-launcher-target"))
			}
		})
	})
})
