package hallpass

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"

	"code.justin.tv/cb/hallpass/view"
	"code.justin.tv/foundation/twitchclient"
)

func (c *client) CreateV1Editor(ctx context.Context, grantedForID string, params *view.CreateEditorRequest, reqOpts *twitchclient.ReqOpts) (*view.CreateEditorResponse, error) {
	path := fmt.Sprintf("/v1/permissions/channels/%s/editors", grantedForID)
	response := &view.CreateEditorResponse{}

	mergedOpts := twitchclient.MergeReqOpts(reqOpts, twitchclient.ReqOpts{
		StatName:       "service.cb-hallpass.v1.create_permissions",
		StatSampleRate: 0.1,
	})

	body := &bytes.Buffer{}
	err := json.NewEncoder(body).Encode(params)
	if err != nil {
		return nil, err
	}

	req, err := c.NewRequest(http.MethodPost, path, body)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/json")

	_, err = c.DoJSON(ctx, response, req, mergedOpts)
	if err != nil {
		return nil, err
	}

	return response, nil
}
