/**
 * Profile avatar storage — native R2 binding (symmetric with GET proxy).
 */
import type { Env } from '../env'

export const MAX_PROFILE_AVATAR_BYTES = 5 * 1024 * 1024

const CONTENT_TYPE_EXT: Record<'image/png' | 'image/jpeg' | 'image/webp', string> = {
  'image/png': 'png',
  'image/jpeg': 'jpg',
  'image/webp': 'webp',
}

export function buildProfileAvatarKey(
  tenantId: string,
  userId: string,
  contentType: 'image/png' | 'image/jpeg' | 'image/webp',
): string {
  const ext = CONTENT_TYPE_EXT[contentType]
  const uid = crypto.randomUUID()
  return `avatars/${tenantId}/${userId}/${uid}.${ext}`
}

export function buildProfileAvatarPublicUrl(r2Key: string): string {
  return `/api/profile/avatar/${r2Key}`
}

const AVATAR_PUBLIC_URL_PREFIX = '/api/profile/avatar/'

/** Extract R2 object key from a profile avatar public URL, or null if not ours. */
export function profileAvatarKeyFromPublicUrl(avatarUrl: string): string | null {
  if (!avatarUrl.startsWith(AVATAR_PUBLIC_URL_PREFIX)) {
    return null
  }
  const key = avatarUrl.slice(AVATAR_PUBLIC_URL_PREFIX.length)
  if (!key || key.includes('..') || key.includes('\\') || key.startsWith('/')) {
    return null
  }
  return key
}

export async function storeProfileAvatar(
  env: Env,
  tenantId: string,
  userId: string,
  contentType: 'image/png' | 'image/jpeg' | 'image/webp',
  bytes: ArrayBuffer | Uint8Array,
): Promise<{ avatar_url: string }> {
  const r2Key = buildProfileAvatarKey(tenantId, userId, contentType)
  await env.STORAGE.put(r2Key, bytes, {
    httpMetadata: { contentType },
  })
  return { avatar_url: buildProfileAvatarPublicUrl(r2Key) }
}
