package query_data

import (
	"fmt"
	"net/http"
	"testing"

	"github.com/contiamo/dev/tests/integration/suite"
)

type Payload suite.Payload

func TestQueryData(t *testing.T) {
	s := suite.New(t)
	s.Run("create new external datasource", func(s *suite.Suite) {
		path := fmt.Sprintf("/hub/api/v1/%s/datasources", s.ProjectID)
		payload := Payload{
			"name":           "foodmart",
			"type":           "external",
			"technology":     "hsqldb-foodmart",
			"connectionInfo": Payload{},
		}
		resp := s.Post(path, payload)
		defer resp.Body.Close()
		s.Require().Equal(http.StatusCreated, resp.StatusCode)
	})

	s.Run("check if we can query the datasource", func(s *suite.Suite) {
		path := fmt.Sprintf("/hub/api/v1/%s/query", s.ProjectID)
		resp := s.Post(path, Payload{
			"sql": `SELECT * FROM "foodmart"."ACCOUNT"`,
		})
		defer resp.Body.Close()
		data := s.ParsePayload(resp.Body)
		hits := s.Jq(data, `.rows[]`)
		s.Require().Len(hits, 11)
	})

	s.Run("delete the datasource", func(s *suite.Suite) {
		path := fmt.Sprintf("/hub/api/v1/%s/datasources/foodmart", s.ProjectID)
		resp := s.Delete(path)
		defer resp.Body.Close()
		s.Require().Equal(http.StatusNoContent, resp.StatusCode)
	})
}
