package testlogger

import (
	"bytes"
	"io"
	"log/slog"
	"testing"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/logz"
)

var (
	_ io.Writer = (*tWriter)(nil)
)

func NewHandler(t testing.TB) slog.Handler {
	return slog.NewTextHandler(
		&tWriter{t: t},
		&slog.HandlerOptions{
			AddSource: true,
			Level:     slog.LevelDebug,
			ReplaceAttr: func(groups []string, attr slog.Attr) slog.Attr {
				return logz.TrimSourceFilePath(attr)
			},
		},
	)
}

func New(t testing.TB) *slog.Logger {
	return slog.New(NewHandler(t))
}

type tWriter struct {
	t testing.TB
}

func (w *tWriter) Write(data []byte) (int, error) {
	w.t.Log(string(bytes.TrimRight(data, "\r\n")))
	return len(data), nil
}
