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

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

	var err error
	var forgejoReleases []*forgejo_sdk.Release

	if o.getProject().forgejoProject.HasReleases {

		owner := f3_tree.GetOwnerName(o.GetNode())
		projectName := f3_tree.GetProjectName(o.GetNode())

		forgejoReleases, _, err = o.getClient().ListReleases(owner, projectName, forgejo_sdk.ListReleasesOptions{
			ListOptions: forgejo_sdk.ListOptions{Page: page, PageSize: pageSize},
		})
		if err != nil {
			panic(fmt.Errorf("error while listing releases: %v", err))
		}
	}
	return f3_tree.ConvertListed(ctx, o.GetNode(), f3_tree.ConvertToAny(forgejoReleases...)...)
}

func newReleases() generic.NodeDriverInterface {
	return &releases{}
}
