package gitea

import (
	"bytes"
	"io"

	"bitbucket.bit.admin.ch/scm/~u80859501/pierre-bot/internal/pierre"
	"code.gitea.io/sdk/gitea"
)

type Adapter struct {
	client *gitea.Client
}

func New(baseURL, token string) (*Adapter, error) {
	client, err := gitea.NewClient(baseURL, gitea.SetToken(token))
	if err != nil {
		return nil, err
	}
	return &Adapter{
		client: client,
	}, nil
}

func (g *Adapter) GetDiff(owner, repo string, prID int) (io.Reader, error) {
	diff, _, err := g.client.GetPullRequestDiff(owner, repo, int64(prID), gitea.PullRequestDiffOptions{})
	if err != nil {
		return nil, err
	}
	return bytes.NewReader(diff), nil
}

func (g *Adapter) AddComment(owner, repo string, prID int, comment pierre.Comment) error {
	opts := gitea.CreatePullReviewOptions{
		State: gitea.ReviewStateComment,
		Comments: []gitea.CreatePullReviewComment{
			{
				Path:       comment.File,
				Body:       comment.Message,
				NewLineNum: int64(comment.Line),
			},
		},
	}
	_, _, err := g.client.CreatePullReview(owner, repo, int64(prID), opts)
	return err
}
