package internal_test

import (
	"compress/gzip"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"code.justin.tv/spade/code-generator/internal"
	"github.com/stretchr/testify/assert"
)

const data = `
some_yaml:
  - a
  - b
  - c
`

const schema = `
events:
  - name: invariant_ping
    description: An event fired 2 times every second by Data Platform to canary Spade.
    fields:
      - name: sequence_number
        description: A generic sequence number for sequencing multiple events
        type:
          name: long
`

const schemaWithExpectation = schema + `
        expectations:
          - name: values_to_not_be_null
`

func TestGetYamlSchemaFromURL(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		fmt.Fprintln(w, data)
	}))
	defer ts.Close()

	schema, err := internal.GetYamlSchemaFromURL(http.DefaultClient, ts.URL)

	assert.NoError(t, err)
	assert.NotNil(t, schema)
	assert.Equal(t, ts.URL, schema.Source)
}

func TestGetYamlSchemaFromGzipURL(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Encoding", "gzip")

		gz := gzip.NewWriter(w)
		gz.Write([]byte(data))
		gz.Close()
	}))

	defer ts.Close()

	schema, err := internal.GetYamlSchemaFromURL(http.DefaultClient, ts.URL)

	assert.NoError(t, err)
	assert.NotNil(t, schema)
	assert.Equal(t, ts.URL, schema.Source)
}

func TestHasFieldWithExpectation_Expectations(t *testing.T) {
	schema, err := internal.GetYamlSchema("hardcode", strings.NewReader(schemaWithExpectation))
	assert.NoError(t, err)

	assert.True(t, schema.HasAnyExpectations())
	assert.True(t, schema.HasFieldWithExpectation(internal.ValuesToNotBeNull))
	assert.False(t, schema.HasFieldWithExpectation(internal.ValuesToMatchRegexList))
}

func TestHasFieldWithExpectation_NoExpectations(t *testing.T) {
	schema, err := internal.GetYamlSchema("hardcode", strings.NewReader(schema))
	assert.NoError(t, err)

	assert.False(t, schema.HasAnyExpectations())
	assert.False(t, schema.HasFieldWithExpectation(internal.ValuesToNotBeNull))
	assert.False(t, schema.HasFieldWithExpectation(internal.ValuesToMatchRegexList))
}
