// Copyright F3 Authors
// SPDX-License-Identifier: MIT

package forgejo

import (
	"context"
	"fmt"
	"strings"

	"code.forgejo.org/f3/gof3/v3/f3"
	"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, node generic.NodeInterface, _ generic.ListOptions, page int) generic.ChildrenList {
	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, node, f3_tree.ConvertToAny(userFounds...)...)
}

func (o *users) LookupMappedID(ctx context.Context, id id.NodeID, f f3.Interface) id.NodeID {
	user := f.(*f3.User)
	return o.GetIDFromName(ctx, user.UserName)
}

func (o *users) GetIDFromName(ctx context.Context, name string) id.NodeID {
	o.Trace("%s", name)
	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{}
}
