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

package gitlab

import (
	"context"
	"fmt"
	"net/http"

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

	"gitlab.com/gitlab-org/api/client-go"
)

type organizations struct {
	container
}

func (o *organizations) listOrganizationsPage(ctx context.Context, page int) []*gitlab.Group {
	pageSize := o.getPageSize()

	var organizationFounds []*gitlab.Group
	var err error
	organizationFounds, _, err = o.getClient().Groups.ListGroups(&gitlab.ListGroupsOptions{
		ListOptions: gitlab.ListOptions{Page: page, PerPage: pageSize},
	})
	if err != nil {
		panic(fmt.Errorf("error while listing organizations: %v", err))
	}

	return organizationFounds
}

func (o *organizations) ListPage(ctx context.Context, page int) generic.ChildrenSlice {
	return f3_tree.ConvertListed(ctx, o.GetNode(), f3_tree.ConvertToAny(o.listOrganizationsPage(ctx, page)...)...)
}

func (o *organizations) GetIDFromName(ctx context.Context, name string) id.NodeID {
	organization, resp, err := o.getClient().Groups.GetGroup(name, &gitlab.GetGroupOptions{})
	if resp.StatusCode == http.StatusNotFound {
		return id.NilID
	}
	if err != nil {
		panic(fmt.Errorf("organization %v %w", o, err))
	}
	return id.NewNodeID(organization.ID)
}

func newOrganizations() generic.NodeDriverInterface {
	return &organizations{}
}
