package deps

import (
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/aquasecurity/trivy/pkg/fanal/analyzer"
	"github.com/aquasecurity/trivy/pkg/fanal/types"
)

func Test_depsLibraryAnalyzer_Analyze(t *testing.T) {
	tests := []struct {
		name      string
		inputFile string
		want      *analyzer.AnalysisResult
		wantErr   string
	}{
		{
			name:      "happy path",
			inputFile: "testdata/datacollector.deps.json",
			want: &analyzer.AnalysisResult{
				Applications: []types.Application{
					{
						Type:     types.DotNetCore,
						FilePath: "testdata/datacollector.deps.json",
						Packages: types.Packages{
							{
								ID:           "Microsoft.VisualStudio.TestPlatform.Common/17.2.0-release-20220408-11",
								Name:         "Microsoft.VisualStudio.TestPlatform.Common",
								Version:      "17.2.0-release-20220408-11",
								Relationship: types.RelationshipRoot,
								Locations: []types.Location{
									{
										StartLine: 15,
										EndLine:   19,
									},
								},
							},
							{
								ID:      "Newtonsoft.Json/9.0.1",
								Name:    "Newtonsoft.Json",
								Version: "9.0.1",
								Locations: []types.Location{
									{
										StartLine: 8,
										EndLine:   14,
									},
								},
							},
						},
					},
				},
			},
		},
		{
			name:      "sad path",
			inputFile: "testdata/invalid.txt",
			wantErr:   ".Net Core dependencies analysis error",
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			f, err := os.Open(tt.inputFile)
			require.NoError(t, err)
			defer f.Close()

			a := depsLibraryAnalyzer{}
			ctx := t.Context()
			got, err := a.Analyze(ctx, analyzer.AnalysisInput{
				FilePath: tt.inputFile,
				Content:  f,
			})

			if tt.wantErr != "" {
				require.ErrorContains(t, err, tt.wantErr)
				return
			}

			require.NoError(t, err)
			assert.Equal(t, tt.want, got)
		})
	}
}

func Test_depsLibraryAnalyzer_Required(t *testing.T) {
	tests := []struct {
		name     string
		filePath string
		want     bool
	}{
		{
			name:     "config",
			filePath: "test/datacollector.deps.json",
			want:     true,
		},
		{
			name:     "zip",
			filePath: "test.zip",
			want:     false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			a := depsLibraryAnalyzer{}
			got := a.Required(tt.filePath, nil)
			assert.Equal(t, tt.want, got)
		})
	}
}
