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

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

	var err error
	var forgejoAttachments []*forgejo_sdk.Attachment

	owner := f3_tree.GetOwnerName(o.GetNode())
	project := f3_tree.GetProjectName(o.GetNode())
	attachable := f3_tree.GetAttachable(o.GetNode())
	attachableID := f3_tree.GetAttachableID(o.GetNode())

	switch attachable.GetKind() {
	case f3_tree.KindRelease:
		forgejoAttachments, _, err = o.getClient().ListReleaseAttachments(owner, project, attachableID, forgejo_sdk.ListReleaseAttachmentsOptions{
			ListOptions: forgejo_sdk.ListOptions{Page: page, PageSize: pageSize},
		})
	case f3_tree.KindComment:
		forgejoAttachments, _, err = o.getClient().ListCommentAttachments(owner, project, attachableID)
	case f3_tree.KindIssue, f3_tree.KindPullRequest:
		forgejoAttachments, _, err = o.getClient().ListIssueAttachments(owner, project, attachableID)
	default:
		panic(fmt.Errorf("unexpected type %s", attachable.GetKind()))
	}

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

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

func newAttachments() generic.NodeDriverInterface {
	return &attachments{}
}
