package suite

import (
	"fmt"
	"net/http"
)

// Setup attempts to create a new project for the test suite. When it is successfully created,
// the id of the project can be accessed using s.ProjectID
func (s *Suite) Setup(projectName string) error {
	if s.currentUser == "" || s.doubleCookie == "" {
		return fmt.Errorf("must be authenticated to setup the test suite")
	}

	if s.TenantID == "" {
		return fmt.Errorf("tenant id is not set")
	}

	path := fmt.Sprintf("/auth/api/v2/tenants/%s/realms", s.TenantID)
	payload := Payload{
		"name":               projectName,
		"addCreatorAsMember": true,
		"tenantId":           s.TenantID,
	}
	resp := s.Post(path, payload)
	defer resp.Body.Close()
	s.Require().Equal(http.StatusOK, resp.StatusCode, "incorrect status code during project creation")

	createResponse := s.ParsePayload(resp.Body)
	id, ok := createResponse["id"].(string)
	s.Require().True(ok, "can not find id in project creation response")
	s.ProjectID = id

	return nil
}
