// 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 goldmane

import (
	"context"
	"testing"
	"time"

	. "github.com/onsi/gomega"
	"github.com/stretchr/testify/mock"

	climocks "github.com/projectcalico/calico/goldmane/pkg/client/mocks"
	"github.com/projectcalico/calico/goldmane/proto"
	"github.com/projectcalico/calico/lib/httpmachinery/pkg/apiutil"
	whiskerv1 "github.com/projectcalico/calico/whisker-backend/pkg/apis/v1"
)

// TestBackendListParameterConversion verifies that List translates ListFlowsParams
// (sort options, time bounds, and filters) into the expected proto.FlowListRequest
// before handing it to the underlying Goldmane client.
func TestBackendListParameterConversion(t *testing.T) {
	RegisterTestingT(t)

	now := time.Now()
	params := whiskerv1.ListFlowsParams{
		Page: 2, PageSize: 50,
		SortBy: whiskerv1.SortBys{
			whiskerv1.SortBy(proto.SortBy_SourceType), whiskerv1.SortBy(proto.SortBy_SourceNamespace), whiskerv1.SortBy(proto.SortBy_SourceName),
			whiskerv1.SortBy(proto.SortBy_DestType), whiskerv1.SortBy(proto.SortBy_DestNamespace), whiskerv1.SortBy(proto.SortBy_DestName),
			whiskerv1.SortBy(proto.SortBy_Time),
		},
		StartTimeGte: now.Unix(),
		Filters: whiskerv1.Filters{
			Policies: []whiskerv1.PolicyMatch{{
				Kind:      whiskerv1.PolicyKindCalicoNetworkPolicy,
				Tier:      whiskerv1.NewFilterMatch("default-tier", whiskerv1.MatchTypeExact),
				Name:      whiskerv1.NewFilterMatch("name", whiskerv1.MatchTypeExact),
				Namespace: whiskerv1.NewFilterMatch("namespace", whiskerv1.MatchTypeExact),
			}},
			SourceNamespaces: []whiskerv1.FilterMatch[string]{{V: "src-ns"}},
			SourceNames:      []whiskerv1.FilterMatch[string]{{V: "src-name"}},
			DestNamespaces:   []whiskerv1.FilterMatch[string]{{V: "dst-ns"}},
			DestNames:        []whiskerv1.FilterMatch[string]{{V: "dst-name"}},
			Protocols:        []whiskerv1.FilterMatch[string]{{V: "tcp"}},
			DestPorts:        []whiskerv1.FilterMatch[int64]{{V: 6060}},
			Actions:          whiskerv1.Actions{whiskerv1.Action(proto.Action_Pass), whiskerv1.Action(proto.Action_Allow)},
			PendingActions:   whiskerv1.PendingActions{whiskerv1.Action(proto.Action_Pass), whiskerv1.Action(proto.Action_Allow)},
			Reporter:         whiskerv1.ReporterSrc,
		},
	}

	expected := &proto.FlowListRequest{
		Page:     2,
		PageSize: 50,
		SortBy: []*proto.SortOption{
			{SortBy: proto.SortBy_SourceType}, {SortBy: proto.SortBy_SourceNamespace}, {SortBy: proto.SortBy_SourceName},
			{SortBy: proto.SortBy_DestType}, {SortBy: proto.SortBy_DestNamespace}, {SortBy: proto.SortBy_DestName},
			{SortBy: proto.SortBy_Time},
		},
		StartTimeGte: now.Unix(),
		Filter: &proto.Filter{
			Policies: []*proto.PolicyMatch{{
				Kind:      proto.PolicyKind_CalicoNetworkPolicy,
				Tier:      &proto.StringMatch{Value: "default-tier"},
				Name:      &proto.StringMatch{Value: "name"},
				Namespace: &proto.StringMatch{Value: "namespace"},
			}},
			SourceNamespaces: []*proto.StringMatch{{Value: "src-ns"}},
			SourceNames:      []*proto.StringMatch{{Value: "src-name"}},
			DestNamespaces:   []*proto.StringMatch{{Value: "dst-ns"}},
			DestNames:        []*proto.StringMatch{{Value: "dst-name"}},
			Protocols:        []*proto.StringMatch{{Value: "tcp"}},
			DestPorts:        []*proto.PortMatch{{Port: 6060}},
			Actions:          []proto.Action{proto.Action_Pass, proto.Action_Allow},
			PendingActions:   []proto.Action{proto.Action_Pass, proto.Action_Allow},
			Reporter:         proto.Reporter_Src,
		},
	}

	var req *proto.FlowListRequest
	cli := new(climocks.FlowsClient)
	cli.On("List", mock.Anything, mock.MatchedBy(func(arg *proto.FlowListRequest) bool {
		req = arg
		return true
	})).Return(nil, nil, context.Canceled).Once()

	_, _, err := NewBackend(cli).List(context.Background(), params)
	Expect(err).To(HaveOccurred())
	Expect(req.String()).To(Equal(expected.String()))
}

// TestBackendStreamParameterConversion verifies that Stream translates the time
// bound and filters of ListFlowsParams into the expected proto.FlowStreamRequest.
func TestBackendStreamParameterConversion(t *testing.T) {
	RegisterTestingT(t)

	now := time.Now()
	params := whiskerv1.ListFlowsParams{
		StartTimeGte: now.Unix(),
		Filters: whiskerv1.Filters{
			SourceNamespaces: []whiskerv1.FilterMatch[string]{{V: "src-ns"}},
			SourceNames:      []whiskerv1.FilterMatch[string]{{V: "src-name"}},
			DestNamespaces:   []whiskerv1.FilterMatch[string]{{V: "dst-ns"}},
			DestNames:        []whiskerv1.FilterMatch[string]{{V: "dst-name"}},
			Protocols:        []whiskerv1.FilterMatch[string]{{V: "tcp"}},
			DestPorts:        []whiskerv1.FilterMatch[int64]{{V: 6060}},
			Actions:          whiskerv1.Actions{whiskerv1.Action(proto.Action_Pass), whiskerv1.Action(proto.Action_Allow)},
			PendingActions:   whiskerv1.PendingActions{whiskerv1.Action(proto.Action_Pass), whiskerv1.Action(proto.Action_Allow)},
			Reporter:         whiskerv1.ReporterSrc,
			Policies: []whiskerv1.PolicyMatch{{
				Kind:      whiskerv1.PolicyKindCalicoNetworkPolicy,
				Tier:      whiskerv1.NewFilterMatch("default-tier", whiskerv1.MatchTypeExact),
				Name:      whiskerv1.NewFilterMatch("name", whiskerv1.MatchTypeExact),
				Namespace: whiskerv1.NewFilterMatch("namespace", whiskerv1.MatchTypeExact),
				Action:    whiskerv1.ActionDeny,
			}},
		},
	}

	expected := &proto.FlowStreamRequest{
		StartTimeGte: now.Unix(),
		Filter: &proto.Filter{
			SourceNamespaces: []*proto.StringMatch{{Value: "src-ns"}},
			SourceNames:      []*proto.StringMatch{{Value: "src-name"}},
			DestNamespaces:   []*proto.StringMatch{{Value: "dst-ns"}},
			DestNames:        []*proto.StringMatch{{Value: "dst-name"}},
			Protocols:        []*proto.StringMatch{{Value: "tcp"}},
			DestPorts:        []*proto.PortMatch{{Port: 6060}},
			Actions:          []proto.Action{proto.Action_Pass, proto.Action_Allow},
			PendingActions:   []proto.Action{proto.Action_Pass, proto.Action_Allow},
			Reporter:         proto.Reporter_Src,
			Policies: []*proto.PolicyMatch{{
				Kind:      proto.PolicyKind_CalicoNetworkPolicy,
				Tier:      &proto.StringMatch{Value: "default-tier"},
				Name:      &proto.StringMatch{Value: "name"},
				Namespace: &proto.StringMatch{Value: "namespace"},
				Action:    proto.Action_Deny,
			}},
		},
	}

	var req *proto.FlowStreamRequest
	cli := new(climocks.FlowsClient)
	cli.On("Stream", mock.Anything, mock.MatchedBy(func(arg *proto.FlowStreamRequest) bool {
		req = arg
		return true
	})).Return(nil, context.Canceled).Once()

	_, err := NewBackend(cli).Stream(context.Background(), params)
	Expect(err).To(HaveOccurred())
	Expect(req.String()).To(Equal(expected.String()))
}

// TestBackendFilterHintsParameterConversion verifies that FilterHints translates
// the hint type, pagination and filters into the expected proto.FilterHintsRequest
// before handing it to the underlying Goldmane client.
func TestBackendFilterHintsParameterConversion(t *testing.T) {
	RegisterTestingT(t)

	ft := whiskerv1.FilterType(proto.FilterType_FilterTypeDestName)
	params := whiskerv1.FlowFilterHintsRequest{
		Pagination: whiskerv1.Pagination{Page: 3, PageSize: 25},
		Type:       &ft,
		Filters: whiskerv1.Filters{
			SourceNamespaces: []whiskerv1.FilterMatch[string]{{V: "src-ns"}},
			DestNames:        []whiskerv1.FilterMatch[string]{{V: "dst-name"}},
			Actions:          whiskerv1.Actions{whiskerv1.Action(proto.Action_Allow)},
		},
	}

	expected := &proto.FilterHintsRequest{
		Type:     proto.FilterType_FilterTypeDestName,
		Page:     3,
		PageSize: 25,
		Filter: &proto.Filter{
			SourceNamespaces: []*proto.StringMatch{{Value: "src-ns"}},
			DestNames:        []*proto.StringMatch{{Value: "dst-name"}},
			Actions:          []proto.Action{proto.Action_Allow},
		},
	}

	var req *proto.FilterHintsRequest
	cli := new(climocks.FlowsClient)
	cli.On("FilterHints", mock.Anything, mock.MatchedBy(func(arg *proto.FilterHintsRequest) bool {
		req = arg
		return true
	})).Return(nil, nil, context.Canceled).Once()

	_, _, err := NewBackend(cli).FilterHints(context.Background(), params, nil)
	Expect(err).To(HaveOccurred())
	Expect(req.String()).To(Equal(expected.String()))
}

// TestBackendFilterHintsDisplayValues verifies that the side-agnostic Name and Namespace hints
// translate Goldmane's stored values for external endpoints into their display values.
func TestBackendFilterHintsDisplayValues(t *testing.T) {
	RegisterTestingT(t)

	tests := []hintDisplayCase{
		{proto.FilterType_FilterTypeName, "pub", "PUBLIC NETWORK"},
		{proto.FilterType_FilterTypeNamespace, "-", "Global"},
		{proto.FilterType_FilterTypeName, "coredns", "coredns"},
	}
	for _, tc := range tests {
		cli := new(climocks.FlowsClient)
		cli.On("FilterHints", mock.Anything, mock.Anything).Return(&proto.ListMetadata{}, []*proto.FilterHint{{Value: tc.stored}}, nil).Once()

		ft := whiskerv1.FilterType(tc.typ)
		_, hints, err := NewBackend(cli).FilterHints(context.Background(), whiskerv1.FlowFilterHintsRequest{Type: &ft}, nil)
		Expect(err).NotTo(HaveOccurred())
		Expect(hints).To(HaveLen(1))
		Expect(hints[0].Value).To(Equal(tc.want), tc.typ.String())
	}
}

type hintDisplayCase struct {
	typ    proto.FilterType
	stored string
	want   string
}

func TestBackendFilterHints_RejectsFlowFilter(t *testing.T) {
	RegisterTestingT(t)

	// Goldmane's FilterHints API returns hint values, not source flows, so a
	// flow-level RBAC predicate cannot be applied; supplying one must fail
	// loudly rather than silently returning unfiltered hints.
	b := NewBackend(climocks.NewFlowsClient(t))

	ft := whiskerv1.FilterType(proto.FilterType_FilterTypeSourceNamespace)
	_, _, err := b.FilterHints(context.Background(), whiskerv1.FlowFilterHintsRequest{Type: &ft},
		func(*whiskerv1.FlowResponse) (bool, error) { return true, nil })
	Expect(err).To(HaveOccurred())
	Expect(err.Error()).To(ContainSubstring("does not support flow filtering"))
}

// TestBackendListMetadataConversion verifies that List and FilterHints carry
// Goldmane's page and result totals through to the apiutil.ListMeta the handler
// serves, and that a response carrying no metadata reads as zero totals.
func TestBackendListMetadataConversion(t *testing.T) {
	RegisterTestingT(t)

	cli := new(climocks.FlowsClient)
	cli.On("List", mock.Anything, mock.Anything).Return(
		&proto.ListMetadata{TotalPages: 5, TotalResults: 212}, []*proto.FlowResult{}, nil).Once()
	cli.On("FilterHints", mock.Anything, mock.Anything).Return(
		&proto.ListMetadata{TotalPages: 3, TotalResults: 17}, []*proto.FilterHint{}, nil).Once()

	b := NewBackend(cli)

	meta, _, err := b.List(context.Background(), whiskerv1.ListFlowsParams{})
	Expect(err).NotTo(HaveOccurred())
	Expect(meta).To(Equal(apiutil.ListMeta{TotalPages: 5, TotalResults: 212}))

	ft := whiskerv1.FilterType(proto.FilterType_FilterTypeSourceNamespace)
	meta, _, err = b.FilterHints(context.Background(), whiskerv1.FlowFilterHintsRequest{Type: &ft}, nil)
	Expect(err).NotTo(HaveOccurred())
	Expect(meta).To(Equal(apiutil.ListMeta{TotalPages: 3, TotalResults: 17}))

	cli.On("List", mock.Anything, mock.Anything).Return(nil, []*proto.FlowResult{}, nil).Once()

	meta, _, err = b.List(context.Background(), whiskerv1.ListFlowsParams{})
	Expect(err).NotTo(HaveOccurred())
	Expect(meta).To(Equal(apiutil.ListMeta{}))
}
