package restorev2_test

import (
	"context"
	"testing"
	"time"

	"github.com/AlekSi/pointer"
	"github.com/stretchr/testify/suite"
	"github.com/tidbcloud/dataflow-service/app/repo/entity"
	"github.com/tidbcloud/dataflow-service/internal/model/util"
)

type pitRestoreTestSuite struct {
	suite.Suite
}

func TestPitBackupTestSuite(t *testing.T) {
	suite.Run(t, new(pitRestoreTestSuite))
}

//nolint:funlen
func (s *pitRestoreTestSuite) TestAsyncCreateSuccess() {
	ctx := context.Background()

	ts := make([]int64, 6)
	nowTs := time.Now().Unix()
	for i := 0; i < 6; i++ {
		ts[i] = nowTs + int64(i*100)
	}
	logbackup := entity.LogBackup{
		Updatable: entity.Updatable{
			Base: entity.Base{
				ID: 1001,
			},
		},
		StartTS:       pointer.To(util.TransToTSOStr(ts[0])),
		TruncateUntil: util.TransToTSOStr(ts[1]),
		CheckpointTS:  util.TransToTSOStr(ts[4]),
	}

	backups := []entity.Backup{
		{
			Updatable: entity.Updatable{
				Base: entity.Base{
					ID: 4,
				},
			},
			Status:         entity.BackupStatusSuccess,
			StartTimeStamp: util.TransToTSOStr(ts[5]),
		},
		{
			Updatable: entity.Updatable{
				Base: entity.Base{
					ID: 3,
				},
			},
			Status:         entity.BackupStatusSuccess,
			StartTimeStamp: util.TransToTSOStr(ts[3]),
		},
		{
			Updatable: entity.Updatable{
				Base: entity.Base{
					ID: 2,
				},
			},
			Status:         entity.BackupStatusSuccess,
			StartTimeStamp: util.TransToTSOStr(ts[2]),
		},
		{
			Updatable: entity.Updatable{
				Base: entity.Base{
					ID: 1,
				},
			},
			Status:         entity.BackupStatusSuccess,
			StartTimeStamp: util.TransToTSOStr(ts[0]),
		},
	}
	calRanges := logbackup.GenPiTRTimeRanges(ctx, backups)

	s.Len(calRanges, 2)

	s.Equal(ts[3]+1, calRanges[0].StartTS)
	s.Equal(ts[4], calRanges[0].EndTS)
	s.Equal(entity.ID(3), calRanges[0].Backup.ID)
	s.Equal(logbackup.ID, calRanges[0].LogBackup.ID)

	s.Equal(ts[2]+1, calRanges[1].StartTS)
	s.Equal(ts[4], calRanges[1].EndTS)
	s.Equal(entity.ID(2), calRanges[1].Backup.ID)
	s.Equal(logbackup.ID, calRanges[1].LogBackup.ID)
}
