package mongo

import (
	"context"
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"

	"bit.admedia.com/scm/ad/adpilot-indexing-repo-sync.com/internal/domain"
)

// UpsertOrgRepositoryLink records org ownership of a gateway-imported repository.
func (s *Store) UpsertOrgRepositoryLink(ctx context.Context, link domain.OrgRepositoryLink) error {
	if link.CreatedAt.IsZero() {
		link.CreatedAt = time.Now().UTC()
	}
	filter := bson.M{
		"org_id":  link.OrgID,
		"repo_id": link.RepoID,
	}
	update := bson.M{
		"$setOnInsert": bson.M{
			"org_id":     link.OrgID,
			"repo_id":    link.RepoID,
			"created_at": link.CreatedAt,
		},
	}
	_, err := s.collection(collectionOrgRepoLinks).UpdateOne(ctx, filter, update, options.Update().SetUpsert(true))
	if err != nil {
		return fmt.Errorf("upsert org repository link: %w", err)
	}
	return nil
}

// ListRepoIDsByOrg returns gateway-format repo_ids linked to an org (legacy ad/slug excluded).
func (s *Store) ListRepoIDsByOrg(ctx context.Context, orgID string) ([]string, error) {
	cursor, err := s.collection(collectionOrgRepoLinks).Find(ctx, bson.M{"org_id": orgID})
	if err != nil {
		return nil, fmt.Errorf("list org repository links: %w", err)
	}
	defer cursor.Close(ctx)

	var links []domain.OrgRepositoryLink
	if err := cursor.All(ctx, &links); err != nil {
		return nil, fmt.Errorf("decode org repository links: %w", err)
	}

	repoIDs := make([]string, 0, len(links))
	for _, link := range links {
		repoIDs = append(repoIDs, link.RepoID)
	}
	return repoIDs, nil
}
