// Copyright 2026 MarketAlly. 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"
)

// 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 and load attributes (including primary language)
	for _, p := range pinnedRepos {
		repo := repos[p.RepoID]
		if repo != nil {
			_ = repo.LoadAttributes(ctx)
		}
		p.Repo = repo
	}

	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.TotalMembers = memberCount
	stats.TotalTeams = teamCount

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

	// Total stars across all repos
	stats.TotalStars, err = repo_model.CountOrgRepoStars(ctx, orgID)
	if err != nil {
		// Non-fatal, just log and continue
		stats.TotalStars = 0
	}

	return stats, nil
}
