package gerrit

import (
	"fmt"
	"net/url"

	gerrit "github.com/andygrunwald/go-gerrit"
)

func newGerritWebhookService(client *gerrit.Client) *gerritWebhookService {
	return &gerritWebhookService{client: client}
}

// GerritWebhook contains functions for querying the API provided by the core webhook plugin.
// endpoints Refs: https://github.com/GerritCodeReview/plugins_webhooks/blob/master/src/main/resources/Documentation/rest-api-config.md
type gerritWebhookService struct {
	client *gerrit.Client
}

func (g *gerritWebhookService) List(project string) (map[string]*ProjectHookConfigs, error) {
	endpoints := fmt.Sprintf("/config/server/webhooks~projects/%s/remotes/", url.QueryEscape(project))
	req, err := g.client.NewRequest("GET", endpoints, nil)
	if err != nil {
		return nil, err
	}
	hooks := make(map[string]*ProjectHookConfigs)
	_, err = g.client.Do(req, &hooks)
	if err != nil {
		return nil, err
	}
	return hooks, nil
}

func (g *gerritWebhookService) Get(project, remoteName string) (*ProjectHookConfigs, error) {
	endpoints := fmt.Sprintf("/config/server/webhooks~projects/%s/remotes/%s/", url.QueryEscape(project), url.QueryEscape(remoteName))
	req, err := g.client.NewRequest("GET", endpoints, nil)
	if err != nil {
		return nil, err
	}
	hook := new(ProjectHookConfigs)
	_, err = g.client.Do(req, hook)
	if err != nil {
		return nil, err
	}
	return hook, nil
}

func (g *gerritWebhookService) Create(project, remoteName string, hook *ProjectHookConfigs) (*ProjectHookConfigs, error) {
	endpoints := fmt.Sprintf("/config/server/webhooks~projects/%s/remotes/%s/", url.QueryEscape(project), url.QueryEscape(remoteName))
	req, err := g.client.NewRequest("PUT", endpoints, hook)
	if err != nil {
		return nil, err
	}
	res := new(ProjectHookConfigs)
	_, err = g.client.Do(req, res)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func (g *gerritWebhookService) Delete(project, remoteName string) error {
	endpoints := fmt.Sprintf("/config/server/webhooks~projects/%s/remotes/%s/", url.QueryEscape(project), url.QueryEscape(remoteName))
	req, err := g.client.NewRequest("DELETE", endpoints, nil)
	if err != nil {
		return err
	}
	_, err = g.client.Do(req, nil)
	if err != nil {
		return err
	}
	return nil
}
