package vulnerability

import (
	"testing"
	"time"

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

	"github.com/goharbor/harbor/src/common/rbac"
	"github.com/goharbor/harbor/src/pkg/permission/types"
	"github.com/goharbor/harbor/src/pkg/robot/model"
	"github.com/goharbor/harbor/src/pkg/scan/dao/scan"
	"github.com/goharbor/harbor/src/pkg/scan/postprocessors"
	v1 "github.com/goharbor/harbor/src/pkg/scan/rest/v1"
	"github.com/goharbor/harbor/src/testing/jobservice"
	postprocessorstesting "github.com/goharbor/harbor/src/testing/pkg/scan/postprocessors"
)

func TestRequiredPermissions(t *testing.T) {
	v := &ScanHandler{}
	expected := []*types.Policy{
		{
			Resource: rbac.ResourceRepository,
			Action:   rbac.ActionPull,
		},
		{
			Resource: rbac.ResourceRepository,
			Action:   rbac.ActionScannerPull,
		},
	}

	result := v.RequiredPermissions()

	assert.Equal(t, expected, result, "RequiredPermissions should return correct permissions")
}

func TestPostScan(t *testing.T) {
	v := &ScanHandler{}
	ctx := &jobservice.MockJobContext{}
	artifact := &v1.Artifact{}
	origRp := &scan.Report{}
	rawReport := ""

	mocker := &postprocessorstesting.ScanReportV1ToV2Converter{}
	mocker.On("ToRelationalSchema", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, "original report", nil)
	postprocessors.Converter = mocker
	sr := &v1.ScanRequest{Artifact: artifact}
	refreshedReport, err := v.PostScan(ctx, sr, origRp, rawReport, time.Now(), &model.Robot{})
	assert.Equal(t, "", refreshedReport, "PostScan should return the refreshed report")
	assert.Nil(t, err, "PostScan should not return an error")
}
