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

package forgejo

import (
	"context"
	"fmt"

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

func (o *projects) GetIDFromName(ctx context.Context, name string) id.NodeID {
	owner := f3_tree.GetOwnerName(o.GetNode())
	forgejoProject, resp, err := o.getClient().GetRepo(owner, name)
	if resp.StatusCode == 404 {
		return id.NilID
	}

	if err != nil {
		panic(fmt.Errorf("error GetRepo(%s, %s): %v", owner, name, err))
	}

	return id.NewNodeID(forgejoProject.ID)
}

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

	var err error
	var forgejoProjects []*forgejo_sdk.Repository

	owner := f3_tree.GetOwner(o.GetNode()).ToFormat()
	switch v := owner.(type) {
	case *f3.User:
		forgejoProjects, _, err = o.getClient().ListUserRepos(v.UserName, forgejo_sdk.ListReposOptions{
			ListOptions: forgejo_sdk.ListOptions{Page: page, PageSize: pageSize},
		})
	case *f3.Organization:
		forgejoProjects, _, err = o.getClient().ListOrgRepos(v.Name, forgejo_sdk.ListOrgReposOptions{
			ListOptions: forgejo_sdk.ListOptions{Page: page, PageSize: pageSize},
		})
	default:
		panic(fmt.Errorf("unexpected type %T", owner))
	}

	if err != nil {
		panic(fmt.Errorf("error while listing projects: %v", err))
	}

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

func newProjects() generic.NodeDriverInterface {
	return &projects{}
}
