// Copyright 2022 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.

package partition

import (
	"testing"

	"github.com/pingcap/tiflow/cdc/model"
	"github.com/stretchr/testify/require"
)

func TestTableDispatcher(t *testing.T) {
	t.Parallel()

	testCases := []struct {
		row             *model.RowChangedEvent
		expectPartition int32
	}{
		{row: &model.RowChangedEvent{
			TableInfo: &model.TableInfo{
				TableName: model.TableName{
					Schema: "test",
					Table:  "t1",
				},
			},
			CommitTs: 1,
		}, expectPartition: 15},
		{row: &model.RowChangedEvent{
			TableInfo: &model.TableInfo{
				TableName: model.TableName{
					Schema: "test",
					Table:  "t1",
				},
			},
			CommitTs: 2,
		}, expectPartition: 15},
		{row: &model.RowChangedEvent{
			TableInfo: &model.TableInfo{
				TableName: model.TableName{
					Schema: "test",
					Table:  "t1",
				},
			},
			CommitTs: 3,
		}, expectPartition: 15},
		{row: &model.RowChangedEvent{
			TableInfo: &model.TableInfo{
				TableName: model.TableName{
					Schema: "test",
					Table:  "t2",
				},
			},
			CommitTs: 1,
		}, expectPartition: 5},
		{row: &model.RowChangedEvent{
			TableInfo: &model.TableInfo{
				TableName: model.TableName{
					Schema: "test",
					Table:  "t2",
				},
			},
			CommitTs: 2,
		}, expectPartition: 5},
		{row: &model.RowChangedEvent{
			TableInfo: &model.TableInfo{
				TableName: model.TableName{
					Schema: "test",
					Table:  "t2",
				},
			},
			CommitTs: 3,
		}, expectPartition: 5},
		{row: &model.RowChangedEvent{
			TableInfo: &model.TableInfo{
				TableName: model.TableName{
					Schema: "test",
					Table:  "t3",
				},
			},
			CommitTs: 3,
		}, expectPartition: 3},
	}
	p := NewTableDispatcher()
	for _, tc := range testCases {
		index, _, err := p.DispatchRowChangedEvent(tc.row, 16)
		require.NoError(t, err)
		require.Equal(t, tc.expectPartition, index)
	}
}
