// Copyright Project Harbor Authors
//
// 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 job

import (
	"context"
	"testing"
	"time"

	"github.com/goharbor/harbor/src/jobservice/common/utils"
	"github.com/goharbor/harbor/src/jobservice/tests"
	"github.com/gomodule/redigo/redis"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"
)

// TrackerTestSuite tests functions of tracker
type TrackerTestSuite struct {
	suite.Suite

	namespace string
	pool      *redis.Pool
}

// TestTrackerTestSuite is entry of go test
func TestTrackerTestSuite(t *testing.T) {
	suite.Run(t, new(TrackerTestSuite))
}

// SetupSuite prepares test suite
func (suite *TrackerTestSuite) SetupSuite() {
	suite.namespace = tests.GiveMeTestNamespace()
	suite.pool = tests.GiveMeRedisPool()
}

// TearDownSuite prepares test suites
func (suite *TrackerTestSuite) TearDownSuite() {
	conn := suite.pool.Get()
	defer func() {
		_ = conn.Close()
	}()

	_ = tests.ClearAll(suite.namespace, conn)
}

// TestTracker tests tracker
func (suite *TrackerTestSuite) TestTracker() {
	jobID := utils.MakeIdentifier()
	mockJobStats := &Stats{
		Info: &StatsInfo{
			JobID:    jobID,
			Status:   SuccessStatus.String(),
			JobKind:  KindGeneric,
			JobName:  SampleJob,
			IsUnique: false,
		},
	}

	tracker := NewBasicTrackerWithStats(
		context.TODO(),
		mockJobStats,
		suite.namespace,
		suite.pool,
		func(hookURL string, change *StatusChange) error {
			return nil
		},
	)

	err := tracker.Save()
	require.Nil(suite.T(), err, "save: nil error expected but got %s", err)

	s, err := tracker.Status()
	assert.Nil(suite.T(), err, "get status: nil error expected but got %s", err)
	assert.Equal(suite.T(), SuccessStatus, s, "get status: expected pending but got %s", s)

	j := tracker.Job()
	assert.Equal(suite.T(), jobID, j.Info.JobID, "job: expect job ID %s but got %s", jobID, j.Info.JobID)

	err = tracker.Update("web_hook_url", "http://hook.url")
	assert.Nil(suite.T(), err, "update: nil error expected but got %s", err)

	err = tracker.Load()
	assert.Nil(suite.T(), err, "load: nil error expected but got %s", err)
	assert.Equal(
		suite.T(),
		"http://hook.url",
		tracker.Job().Info.WebHookURL,
		"web hook: expect %s but got %s",
		"http://hook.url",
		tracker.Job().Info.WebHookURL,
	)

	err = tracker.Run()
	assert.Error(suite.T(), err, "run: non nil error expected but got nil")
	err = tracker.CheckIn("check in")
	assert.Nil(suite.T(), err, "check in: nil error expected but got %s", err)
	err = tracker.Succeed()
	assert.Nil(suite.T(), err, "succeed: nil error expected but got %s", err)
	err = tracker.Stop()
	assert.Nil(suite.T(), err, "stop: nil error expected but got %s", err)
	err = tracker.Fail()
	assert.Nil(suite.T(), err, "fail: nil error expected but got %s", err)

	t := NewBasicTrackerWithID(
		context.TODO(),
		jobID,
		suite.namespace,
		suite.pool,
		func(hookURL string, change *StatusChange) error {
			return nil
		},
	)
	err = t.Load()
	assert.NoError(suite.T(), err)

	err = t.Expire()
	assert.NoError(suite.T(), err)
}

// TestPeriodicTracker tests tracker of periodic
func (suite *TrackerTestSuite) TestPeriodicTracker() {
	jobID := utils.MakeIdentifier()
	nID := time.Now().Unix()
	mockJobStats := &Stats{
		Info: &StatsInfo{
			JobID:      jobID,
			Status:     ScheduledStatus.String(),
			JobKind:    KindPeriodic,
			JobName:    SampleJob,
			IsUnique:   false,
			CronSpec:   "0 0 * * * *",
			NumericPID: nID,
		},
	}

	t := NewBasicTrackerWithStats(context.TODO(), mockJobStats, suite.namespace, suite.pool, nil)
	err := t.Save()
	require.NoError(suite.T(), err)

	executionID := utils.MakeIdentifier()
	runAt := time.Now().Add(1 * time.Hour).Unix()
	executionStats := &Stats{
		Info: &StatsInfo{
			JobID:         executionID,
			Status:        ScheduledStatus.String(),
			JobKind:       KindScheduled,
			JobName:       SampleJob,
			IsUnique:      false,
			CronSpec:      "0 0 * * * *",
			RunAt:         runAt,
			EnqueueTime:   runAt,
			UpstreamJobID: jobID,
		},
	}

	t2 := NewBasicTrackerWithStats(context.TODO(), executionStats, suite.namespace, suite.pool, nil)
	err = t2.Save()
	require.NoError(suite.T(), err)

	id, err := t.NumericID()
	require.NoError(suite.T(), err)
	assert.Equal(suite.T(), nID, id)

	err = t2.PeriodicExecutionDone()
	require.NoError(suite.T(), err)
}

// TestPushForRetry tests push for retry
func (suite *TrackerTestSuite) TestPushForRetry() {
	ID := utils.MakeIdentifier()
	runAt := time.Now().Add(1 * time.Hour).Unix()
	jobStats := &Stats{
		Info: &StatsInfo{
			JobID:       ID,
			Status:      ScheduledStatus.String(),
			JobKind:     KindScheduled,
			JobName:     SampleJob,
			IsUnique:    false,
			RunAt:       runAt,
			EnqueueTime: runAt,
		},
	}

	t := &basicTracker{
		namespace: suite.namespace,
		context:   context.TODO(),
		pool:      suite.pool,
		jobID:     ID,
		jobStats:  jobStats,
		callback:  nil,
	}

	err := t.pushToQueueForRetry(RunningStatus)
	require.NoError(suite.T(), err)
}
