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

package gitlab

import (
	"context"
	"fmt"

	"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 users struct {
	container
}

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

	userFounds, _, err := o.getClient().Users.ListUsers(&gitlab.ListUsersOptions{
		ListOptions: gitlab.ListOptions{Page: page, PerPage: pageSize},
	})
	if err != nil {
		panic(fmt.Errorf("error while listing users: %v", err))
	}

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

func (o *users) GetIDFromName(ctx context.Context, name string) id.NodeID {
	users, _, err := o.getClient().Users.ListUsers(&gitlab.ListUsersOptions{Username: &name})
	if err != nil {
		panic(fmt.Errorf("user %v %w", o, err))
	}
	if len(users) == 0 {
		return id.NilID
	} else if len(users) > 1 {
		panic(fmt.Errorf("user %v found multiple users %v", name, users))
	}
	return id.NewNodeID(users[0].ID)
}

func newUsers() generic.NodeDriverInterface {
	return &users{}
}
