// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package org

import (
	"context"

	"code.gitea.io/gitea/models/organization"
	repo_model "code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/modules/optional"
)

// GetOrgPinnedReposWithDetails returns all pinned repos with repo and group details loaded
func GetOrgPinnedReposWithDetails(ctx context.Context, orgID int64) ([]*organization.OrgPinnedRepo, error) {
	pinnedRepos, err := organization.GetOrgPinnedRepos(ctx, orgID)
	if err != nil {
		return nil, err
	}

	if len(pinnedRepos) == 0 {
		return pinnedRepos, nil
	}

	// Load repos
	repoIDs := make([]int64, len(pinnedRepos))
	for i, p := range pinnedRepos {
		repoIDs[i] = p.RepoID
	}

	repos, err := repo_model.GetRepositoriesMapByIDs(ctx, repoIDs)
	if err != nil {
		return nil, err
	}

	// Load groups
	if err := organization.LoadPinnedRepoGroups(ctx, pinnedRepos, orgID); err != nil {
		return nil, err
	}

	// Attach repos
	for _, p := range pinnedRepos {
		p.Repo = repos[p.RepoID]
	}

	return pinnedRepos, nil
}

// GetOrgOverviewStats returns statistics for the organization overview page
func GetOrgOverviewStats(ctx context.Context, orgID int64) (*organization.OrgOverviewStats, error) {
	stats := &organization.OrgOverviewStats{}

	memberCount, teamCount, err := organization.GetOrgMemberAndTeamCounts(ctx, orgID)
	if err != nil {
		return nil, err
	}
	stats.MemberCount = memberCount
	stats.TeamCount = teamCount

	// Repo counts
	stats.RepoCount, err = repo_model.CountRepositories(ctx, repo_model.CountRepositoryOptions{
		OwnerID: orgID,
	})
	if err != nil {
		return nil, err
	}

	stats.PublicRepoCount, err = repo_model.CountRepositories(ctx, repo_model.CountRepositoryOptions{
		OwnerID: orgID,
		Private: optional.Some(false),
	})
	if err != nil {
		return nil, err
	}

	return stats, nil
}
