// monorepo/cloud/maplefile-backend/internal/maplefile/repo/filemetadata/list_by_tag_id.go
package filemetadata

import (
	"context"
	"fmt"

	"github.com/gocql/gocql"
	dom_file "codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/domain/file"
	"go.uber.org/zap"
)

// ListByTagID retrieves all files that have the specified tag assigned
// Uses the denormalized files_by_tag_id table for efficient lookups
func (impl *fileMetadataRepositoryImpl) ListByTagID(ctx context.Context, tagID gocql.UUID) ([]*dom_file.File, error) {
	impl.Logger.Info("🏷️  REPO: Listing files by tag ID",
		zap.String("tag_id", tagID.String()))

	var fileIDs []gocql.UUID

	// Query the denormalized table
	query := `SELECT file_id FROM maplefile.files_by_tag_id WHERE tag_id = ?`

	iter := impl.Session.Query(query, tagID).WithContext(ctx).Iter()

	var fileID gocql.UUID
	for iter.Scan(&fileID) {
		fileIDs = append(fileIDs, fileID)
	}

	if err := iter.Close(); err != nil {
		impl.Logger.Error("🏷️  REPO: Failed to query files by tag",
			zap.String("tag_id", tagID.String()),
			zap.Error(err))
		return nil, fmt.Errorf("failed to list files by tag: %w", err)
	}

	impl.Logger.Info("🏷️  REPO: Found file IDs for tag",
		zap.String("tag_id", tagID.String()),
		zap.Int("count", len(fileIDs)))

	// Load full file details using existing helper method
	// This will filter to only active files
	files, err := impl.loadMultipleFiles(fileIDs)
	if err != nil {
		impl.Logger.Error("🏷️  REPO: Failed to load files",
			zap.String("tag_id", tagID.String()),
			zap.Error(err))
		return nil, err
	}

	impl.Logger.Info("🏷️  REPO: Successfully loaded files by tag",
		zap.String("tag_id", tagID.String()),
		zap.Int("active_count", len(files)))

	return files, nil
}
