package server

import (
	"net/http"
	"testing"

	"github.com/stretchr/testify/assert"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/httpz"
	"k8s.io/apimachinery/pkg/runtime"
)

func TestProxyHeaders_checkContentTypes(t *testing.T) {
	// GIVEN
	tests := []struct {
		name             string
		h                http.Header
		expectedErrorMsg string
	}{
		// Requests with no Content-Type are allowed
		{
			name: "nil headers -> allow",
			h:    nil,
		},
		{
			name: "missing Content-Type header -> allow",
			h:    http.Header{"Any-Header": []string{"true"}},
		},
		{
			name:             "empty Content-Type header -> reject",
			h:                http.Header{httpz.ContentTypeHeader: []string{""}},
			expectedErrorMsg: "mime: no media type",
		},
		{
			name:             "single disallowed Content-Type header -> reject",
			h:                http.Header{httpz.ContentTypeHeader: []string{"text/html"}},
			expectedErrorMsg: "not allowed: text/html",
		},
		{
			name:             "disallowed Content-Type header among allowed one -> reject",
			h:                http.Header{httpz.ContentTypeHeader: []string{"text/plain", "text/html"}},
			expectedErrorMsg: "not allowed: text/html",
		},
		{
			name: "single allowed Content-Type header -> allow",
			h:    http.Header{httpz.ContentTypeHeader: []string{"text/plain"}},
		},
		{
			name: "multiple allowed Content-Type headers -> allow",
			h:    http.Header{httpz.ContentTypeHeader: []string{"text/plain", runtime.ContentTypeJSON}},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// WHEN
			err := checkContentType(tt.h, allowedResponseContentTypes...)

			if tt.expectedErrorMsg == "" {
				assert.NoError(t, err)
			} else {
				assert.ErrorContains(t, err, tt.expectedErrorMsg)
			}
		})
	}
}
