package internal

import (
	"context"
	"crypto/tls"
	"github.com/pkg/errors"
	"gitlab.com/pcanilho/go-jira"
	"net/http"
)

type jiraController struct {
	client   *jira.Client
	ctx      context.Context
	username string
}

func NewJira(ctx context.Context, username, password, url string, skipVerifyTLS bool) (*jiraController, error) {
	jiraHttpClient := jira.BasicAuthTransport{
		Username: username,
		Password: password,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: skipVerifyTLS},
		},
	}

	client, err := jira.NewClient(jiraHttpClient.Client(), url)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to authenticate with the Jira instance at [%s]", url)
	}

	if ctx == nil {
		ctx = context.Background()
	}
	return &jiraController{ctx: ctx, client: client, username: username}, nil
}