// tdd-guard:skip — thin server-only wrapper around Supabase Storage signed-URL
// generation; behaviour depends on the storage backend, not unit-testable logic.
import { createClient } from '@/lib/supabase/server'

const AVATAR_BUCKET = 'avatars'
// Avatars live in a private bucket (repo convention: every bucket is private +
// signed URLs). One hour is plenty for a single page render.
const SIGNED_TTL_SECONDS = 3600

/** Resolve a stored avatar storage key into a short-lived signed URL. */
export async function resolveAvatarUrl(storageKey: string | null): Promise<string | null> {
  if (!storageKey) return null
  const supabase = await createClient()
  const { data } = await supabase.storage.from(AVATAR_BUCKET).createSignedUrl(storageKey, SIGNED_TTL_SECONDS)
  return data?.signedUrl ?? null
}

/**
 * Batch-resolve avatar storage keys for list views. Returns a map keyed by the
 * original storage key, so callers can look up `map.get(row.avatar_url)`.
 */
export async function resolveAvatarUrls(storageKeys: (string | null)[]): Promise<Map<string, string>> {
  const keys = [...new Set(storageKeys.filter((k): k is string => !!k))]
  if (keys.length === 0) return new Map()
  const supabase = await createClient()
  const { data } = await supabase.storage.from(AVATAR_BUCKET).createSignedUrls(keys, SIGNED_TTL_SECONDS)
  return new Map(
    (data ?? [])
      .filter((d): d is typeof d & { path: string; signedUrl: string } => Boolean(d.path && d.signedUrl))
      .map((d) => [d.path, d.signedUrl])
  )
}
