// Copyright F3 Authors
// 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) ListPage(ctx context.Context, node generic.NodeInterface, _ generic.ListOptions, page int) generic.ChildrenList {
	pageSize := o.getPageSize()

	var err error
	var forgejoProjects []*forgejo_sdk.Repository

	owner := f3_tree.GetOwner(node).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, node, f3_tree.ConvertToAny(forgejoProjects...)...)
}

func (o *projects) LookupMappedID(ctx context.Context, id id.NodeID, f f3.Interface) id.NodeID {
	project := f.(*f3.Project)
	return o.GetIDFromName(ctx, project.Name)
}

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 newProjects() generic.NodeDriverInterface {
	return &projects{}
}
