package drive

import (
	"context"

	"github.com/ultisuite/ulti-backend/internal/nextcloud"
)

func normalizeDriveSourcePath(filePath string) string {
	return nextcloud.NormalizeClientPath(filePath)
}

// EnrichSources attaches suite source metadata (ultimail, ultimeet, …) from drive_file_sources.
func (s *Service) EnrichSources(ctx context.Context, externalUserID string, files []nextcloud.FileInfo) {
	if s.db == nil || externalUserID == "" || len(files) == 0 {
		return
	}

	var userID string
	if err := s.db.QueryRow(ctx, `SELECT id FROM users WHERE external_id = $1`, externalUserID).Scan(&userID); err != nil {
		return
	}

	paths := make([]string, 0, len(files))
	indexes := make([]int, 0, len(files))
	for i, f := range files {
		if f.Type != "file" || f.Path == "" {
			continue
		}
		paths = append(paths, normalizeDriveSourcePath(f.Path))
		indexes = append(indexes, i)
	}
	if len(paths) == 0 {
		return
	}

	rows, err := s.db.Query(ctx, `
		SELECT file_path, source FROM drive_file_sources
		WHERE user_id = $1 AND file_path = ANY($2)
	`, userID, paths)
	if err != nil {
		return
	}
	defer rows.Close()

	byPath := make(map[string]string, len(paths))
	for rows.Next() {
		var filePath, source string
		if err := rows.Scan(&filePath, &source); err != nil {
			continue
		}
		byPath[filePath] = source
	}

	for i, filePath := range paths {
		if source, ok := byPath[filePath]; ok {
			files[indexes[i]].Source = source
		}
	}
}
