package internal

import (
	"encoding/json"
	"fmt"
	"github.com/pkg/errors"
	"gitlab.com/pcanilho/go-jira"
	"io"
	"net/http"
	"strings"
)

const (
	apiUserRoute = "/rest/api/2/user/search?username=%s"
)

func (j *jiraController) GetUser(username string) (*jira.User, error) {
	if len(strings.TrimSpace(username)) == 0 {
		return nil, fmt.Errorf("invalid username specified")
	}

	baseUrl := j.client.GetBaseURL()
	apiUrl := fmt.Sprintf("%s/%s", baseUrl.String(), apiUserRoute)
	req, err := http.NewRequestWithContext(
		j.ctx,
		http.MethodGet,
		fmt.Sprintf(apiUrl, username), nil)

	resp, err := j.client.Do(req, nil)
	if err != nil {
		if resp != nil {
			b, _ := io.ReadAll(resp.Body)
			err = errors.Wrap(err, string(b))
		}
		return nil, errors.Wrapf(err, "unable to find user with the username [%s]", username)
	}

	if resp == nil {
		return nil, errors.Wrapf(err, "an unexpected nil response received from Jira when searching for the user")
	}

	b, _ := io.ReadAll(resp.Body)
	var users []*jira.User
	if err = json.Unmarshal(b, &users); err != nil {
		return nil, errors.Wrap(err, "unable to parse the response as a valid [*jira.User] instance")
	}

	if len(users) == 0 {
		return nil, fmt.Errorf("unable to find a user matching the provided username [%s]", username)
	}

	return users[0], nil
}