// Copyright Earl Warren <contact@earl-warren.org>
// Copyright Loïc Dachary <loic@dachary.org>
// SPDX-License-Identifier: MIT

package forgejo

import (
	"context"
	"fmt"

	f3_tree "code.forgejo.org/f3/gof3/v3/tree/f3"
	"code.forgejo.org/f3/gof3/v3/tree/generic"

	forgejo_sdk "code.forgejo.org/f3/gof3/v3/forges/forgejo/sdk"
)

type reviews struct {
	container
}

func (o *reviews) ListPage(ctx context.Context, page int) generic.ChildrenSlice {
	pageSize := o.getPageSize()

	owner := f3_tree.GetOwnerName(o.GetNode())
	project := f3_tree.GetProjectName(o.GetNode())
	pullRequest := f3_tree.GetPullRequest(o.GetNode())

	reviews, _, err := o.getClient().ListPullReviews(owner, project, pullRequest.GetID().Int64(), forgejo_sdk.ListPullReviewsOptions{
		ListOptions: forgejo_sdk.ListOptions{Page: page, PageSize: pageSize},
	})
	if err != nil {
		panic(fmt.Errorf("error while listing reviews: %v", err))
	}

	reviewsNoSystemUser := make([]*forgejo_sdk.PullReview, 0, len(reviews))
	for _, review := range reviews {
		if getSystemUserByID(review.Reviewer.ID) != nil {
			continue
		}
		reviewsNoSystemUser = append(reviewsNoSystemUser, review)
	}

	return f3_tree.ConvertListed(ctx, o.GetNode(), f3_tree.ConvertToAny(reviewsNoSystemUser...)...)
}

func newReviews() generic.NodeDriverInterface {
	return &reviews{}
}
