package sources

import (
	"context"
	"errors"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"github.com/salvacybersec/keyhunter/pkg/types"
)

func TestClipboardSource_FixtureReader(t *testing.T) {
	src := &ClipboardSource{
		Reader:    func() (string, error) { return "sk-live-xxxxxx", nil },
		ChunkSize: defaultChunkSize,
	}
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	out := make(chan types.Chunk, 4)
	errCh := make(chan error, 1)
	go func() { errCh <- src.Chunks(ctx, out); close(out) }()

	var got []types.Chunk
	for c := range out {
		got = append(got, c)
	}
	require.NoError(t, <-errCh)
	require.Len(t, got, 1)
	require.Equal(t, "clipboard", got[0].Source)
	require.Equal(t, "sk-live-xxxxxx", string(got[0].Data))
}

func TestClipboardSource_ReaderError(t *testing.T) {
	src := &ClipboardSource{
		Reader: func() (string, error) { return "", errors.New("no xclip installed") },
	}
	out := make(chan types.Chunk, 1)
	err := src.Chunks(context.Background(), out)
	require.Error(t, err)
	require.Contains(t, strings.ToLower(err.Error()), "clipboard")
}

func TestClipboardSource_EmptyClipboard(t *testing.T) {
	src := &ClipboardSource{
		Reader: func() (string, error) { return "", nil },
	}
	out := make(chan types.Chunk, 1)
	err := src.Chunks(context.Background(), out)
	require.NoError(t, err)
	require.Len(t, out, 0)
}
