package sources

import (
	"bytes"
	"context"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

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

func TestStdinSource_Basic(t *testing.T) {
	src := NewStdinSourceFrom(bytes.NewBufferString("API_KEY=sk-test-xyz"))
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	out := make(chan types.Chunk, 8)
	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, "stdin", got[0].Source)
	require.Equal(t, "API_KEY=sk-test-xyz", string(got[0].Data))
}

func TestStdinSource_Empty(t *testing.T) {
	src := NewStdinSourceFrom(bytes.NewBuffer(nil))
	out := make(chan types.Chunk, 1)
	err := src.Chunks(context.Background(), out)
	close(out)
	require.NoError(t, err)
	require.Len(t, out, 0)
}

func TestStdinSource_CtxCancel(t *testing.T) {
	// Large buffer so emitByteChunks iterates and can observe cancellation.
	data := make([]byte, 1<<20)
	src := NewStdinSourceFrom(bytes.NewReader(data))
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	out := make(chan types.Chunk) // unbuffered forces select on ctx
	err := src.Chunks(ctx, out)
	require.ErrorIs(t, err, context.Canceled)
}
