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

package forgejo

import (
	"context"
	"fmt"
	"strings"

	"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"

	forgejo_sdk "code.forgejo.org/f3/gof3/v3/forges/forgejo/sdk"
)

type users struct {
	container
}

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

	var userFounds []*forgejo_sdk.User
	var err error
	if o.getIsAdmin() {
		userFounds, _, err = o.getClient().AdminListUsers(forgejo_sdk.AdminListUsersOptions{
			ListOptions: forgejo_sdk.ListOptions{Page: page, PageSize: pageSize},
		})
	} else {
		userFounds, _, err = o.getClient().SearchUsers(forgejo_sdk.SearchUsersOption{
			ListOptions: forgejo_sdk.ListOptions{Page: page, PageSize: pageSize},
		})
	}
	if err != nil {
		panic(fmt.Errorf("error while listing users: %v", err))
	}

	for _, user := range userFounds {
		user.Email = fromFakeEmail(user.Email)
	}

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

func (o *users) GetIDFromName(ctx context.Context, name string) id.NodeID {
	user, resp, err := o.getClient().GetUserInfo(name)
	if resp.StatusCode == 404 {
		return id.NilID
	}
	if err != nil {
		if strings.Contains(err.Error(), "user not found") {
			return id.NilID
		}
		panic(fmt.Errorf("user %v %w", o, err))
	}
	return id.NewNodeID(user.ID)
}

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