package jiracli

import (
	"context"
	"net/http"
	"net/url"
	"time"
)

type Config struct {
	Scheme  string
	Addr    string
	Project string
	Token   string
}

type client struct {
	raw *raw
}

func NewJiraCli(conf Config) (JiraCli, error) {
	httpCli := &http.Client{
		Timeout:   10 * time.Second,
		Transport: http.DefaultTransport,
	}

	// deal with the situation when addr is like internal.something.net/jira
	rootUrl, err := url.Parse(conf.Addr)
	if err != nil {
		return nil, err
	}

	c := &client{
		raw: &raw{
			scheme:     conf.Scheme,
			project:    conf.Project,
			host:       rootUrl.Host,
			rootPath:   rootUrl.Path,
			token:      conf.Token,
			httpClient: httpCli,
		},
	}

	return c, nil
}

func (c *client) GetRoleActors(ctx context.Context, roleId string) ([]string, error) {
	resp, err := c.raw.GetRole(ctx, roleId)
	if err != nil {
		return nil, err
	}

	actorEmails := make([]string, 0, len(resp.Actors))
	for _, actor := range resp.Actors {
		actorEmails = append(actorEmails, actor.Name)
	}

	return actorEmails, nil
}

func (c *client) UpdateRoleActors(ctx context.Context, roleId string, emails []string) error {
	return c.raw.UpdateRoleActors(ctx, roleId, emails)
}
