// Copyright 2026 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,
// 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 ingest

import (
	"sync"
	"testing"
	"time"

	"github.com/pingcap/errors"
	"github.com/pingcap/tidb/pkg/lightning/backend/remote"
	"github.com/stretchr/testify/require"
)

func TestFlushEngineInfosUnlocksBeforeFlushingNextEngine(t *testing.T) {
	first := &engineInfo{indexID: 1, flushLock: &sync.RWMutex{}}
	second := &engineInfo{indexID: 2, flushLock: &sync.RWMutex{}}

	second.flushLock.RLock()
	releasedSecond := make(chan struct{})
	releaseSecond := func() {
		select {
		case <-releasedSecond:
		default:
			second.flushLock.RUnlock()
			close(releasedSecond)
		}
	}
	t.Cleanup(releaseSecond)

	firstFlushed := make(chan struct{})
	flushDone := make(chan error, 1)
	go func() {
		flushDone <- flushEngineInfos([]*engineInfo{first, second}, func(ei *engineInfo) error {
			if ei == first {
				close(firstFlushed)
			}
			return nil
		})
	}()

	<-firstFlushed

	probeDone := make(chan struct{})
	go func() {
		first.flushLock.RLock()
		first.flushLock.RUnlock()
		close(probeDone)
	}()

	select {
	case <-probeDone:
	case <-time.After(time.Second):
		t.Fatal("flush held the previous engine lock while waiting for the next engine")
	}

	releaseSecond()

	select {
	case err := <-flushDone:
		require.NoError(t, err)
	case <-time.After(time.Second):
		t.Fatal("flush did not finish after releasing the blocked engine")
	}
}

func TestIsRemoteBackendNonRetryableError(t *testing.T) {
	require.True(t, IsRemoteBackendNonRetryableError(errors.Trace(remote.ErrDuplicateKey)))
	require.True(t, IsRemoteBackendNonRetryableError(errors.Trace(remote.ErrOverlap)))
	require.True(t, IsRemoteBackendNonRetryableError(errors.New("task stopped with state reverted, err too many duplicate key")))
	require.True(t, IsRemoteBackendNonRetryableError(errors.New("task stopped with state reverted, err region has overlap data")))
	require.True(t, IsRemoteBackendNonRetryableError(errors.New("data size 123 exceeds max data size 100")))

	require.False(t, IsRemoteBackendNonRetryableError(remote.ErrTaskCanceled))
	require.False(t, IsRemoteBackendNonRetryableError(remote.ErrFlushRemoteWorker))
	require.False(t, IsRemoteBackendNonRetryableError(errors.New("unknown import error")))
}
