// 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 reactions struct {
	container
}

func (o *reactions) ListPage(ctx context.Context, page int) generic.ChildrenSlice {
	var err error
	var forgejoReactions []*forgejo_sdk.Reaction

	owner := f3_tree.GetOwnerName(o.GetNode())
	project := f3_tree.GetProjectName(o.GetNode())
	reactionable := f3_tree.GetReactionable(o.GetNode())
	reactionableID := f3_tree.GetReactionableID(o.GetNode())

	switch reactionable.GetKind() {
	case f3_tree.KindIssue, f3_tree.KindPullRequest:
		forgejoReactions, _, err = o.getClient().GetIssueReactions(owner, project, reactionableID)
	case f3_tree.KindComment:
		forgejoReactions, _, err = o.getClient().GetIssueCommentReactions(owner, project, reactionableID)
	default:
		panic(fmt.Errorf("unexpected type %T", owner))
	}

	if err != nil {
		panic(fmt.Errorf("error while listing reactions: %v", err))
	}

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

func newReactions() generic.NodeDriverInterface {
	return &reactions{}
}
