package log

import (
	"bytes"
	"context"
	"testing"

	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/labkit/correlation"
)

func TestContextLogger(t *testing.T) {
	tests := []struct {
		name          string
		correlationID string
		matchRegExp   string
	}{
		{
			name:          "none",
			correlationID: "",
			matchRegExp:   `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*level=info msg=Hello correlation_id=\n$`,
		},
		{
			name:          "set",
			correlationID: "123456",
			matchRegExp:   `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*level=info msg=Hello correlation_id=123456\n$`,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			buf := &bytes.Buffer{}
			closer, err := Initialize(WithWriter(buf))
			require.NoError(t, err)
			defer closer.Close()

			ctx := context.Background()
			if tt.correlationID != "" {
				ctx = correlation.ContextWithCorrelation(ctx, tt.correlationID)
			}

			ContextLogger(ctx).Info("Hello")
			require.Regexp(t, tt.matchRegExp, buf.String())
		})
	}
}

func TestWithContextFields(t *testing.T) {
	tests := []struct {
		name          string
		correlationID string
		fields        Fields
		matchRegExp   string
	}{
		{
			name:          "none",
			correlationID: "",
			fields:        nil,
			matchRegExp:   `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*level=info msg=Hello correlation_id=\n$`,
		},
		{
			name:          "single",
			correlationID: "123456",
			fields:        Fields{"field": "value"},
			matchRegExp:   `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*level=info msg=Hello correlation_id=123456 field=value\n$`,
		},
		{
			name:          "multiple",
			correlationID: "123456",
			fields:        Fields{"field": "value", "field2": "value2"},
			matchRegExp:   `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*level=info msg=Hello correlation_id=123456 field=value field2=value2\n$`,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			buf := &bytes.Buffer{}
			closer, err := Initialize(WithWriter(buf))
			require.NoError(t, err)
			defer closer.Close()

			ctx := context.Background()
			if tt.correlationID != "" {
				ctx = correlation.ContextWithCorrelation(ctx, tt.correlationID)
			}

			WithContextFields(ctx, tt.fields).Info("Hello")
			require.Regexp(t, tt.matchRegExp, buf.String())
		})
	}
}

func TestContextFields(t *testing.T) {
	tests := []struct {
		name          string
		correlationID string
		fields        Fields
	}{
		{
			name:          "none",
			correlationID: "",
			fields:        Fields{correlation.FieldName: ""},
		},
		{
			name:          "single",
			correlationID: "123456",
			fields:        Fields{correlation.FieldName: "123456"},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			ctx := context.Background()
			if tt.correlationID != "" {
				ctx = correlation.ContextWithCorrelation(ctx, tt.correlationID)
			}

			got := ContextFields(ctx)
			require.Equal(t, tt.fields, got)
		})
	}
}
