package log

import (
	"bytes"
	"fmt"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestNew(t *testing.T) {
	buf := &bytes.Buffer{}
	logger := New()
	logger.SetOutput(buf)

	logger.Info("Hello")
	require.Regexp(t, `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*level=info msg=Hello\n$`, buf.String())
}

func TestInfo(t *testing.T) {
	buf := &bytes.Buffer{}
	closer, err := Initialize(WithWriter(buf))
	require.NoError(t, err)
	defer closer.Close()

	Info("Information")
	require.Regexp(t, `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*level=info msg=Information\n$`, buf.String())
}

func TestWithField(t *testing.T) {
	buf := &bytes.Buffer{}
	closer, err := Initialize(WithWriter(buf))
	require.NoError(t, err)
	defer closer.Close()

	WithField("field", "value").Warn("notice")
	require.Regexp(t, `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*level=warning msg=notice field=value\n$`, buf.String())
}

func TestWithFields(t *testing.T) {
	buf := &bytes.Buffer{}
	closer, err := Initialize(WithWriter(buf))
	require.NoError(t, err)
	defer closer.Close()

	WithFields(Fields{"field": "value", "field2": "value2"}).Warn("another")
	require.Regexp(t, `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*level=warning msg=another field=value field2=value2\n$`, buf.String())
}

func TestWithError(t *testing.T) {
	buf := &bytes.Buffer{}
	closer, err := Initialize(WithWriter(buf))
	require.NoError(t, err)
	defer closer.Close()

	WithError(fmt.Errorf("fail")).Error("rejected")
	require.Regexp(t, `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*level=error msg=rejected error=fail\n$`, buf.String())
}
