import type { UserProfile } from '@/types/domain'
import { gradientAvatarKey } from './avatar'

// Cloud records created at different times may miss nested fields (preferences/stats).
// Normalize every user crossing the service boundary so the UI never reads undefined.
export function normalizeUser(user?: Partial<UserProfile> | null): UserProfile {
  return {
    _id: user?._id || '',
    openid: user?.openid,
    nickname: user?.nickname || '宠物达人',
    handle: user?.handle || '',
    // Stable, identity-derived gradient when no avatarKey was stored.
    avatarKey: user?.avatarKey || gradientAvatarKey(user?._id || user?.openid || user?.nickname),
    avatarUrl: user?.avatarUrl || '',
    profileCompleted: Boolean(user?.profileCompleted),
    location: user?.location || '',
    yearsWithPets: user?.yearsWithPets || 0,
    level: user?.level || 1,
    bio: user?.bio || '',
    verified: Boolean(user?.verified),
    stats: {
      posts: user?.stats?.posts || 0,
      following: user?.stats?.following || 0,
      followers: user?.stats?.followers || 0
    },
    preferences: {
      notifications: user?.preferences?.notifications ?? true,
      nearbyVisible: user?.preferences?.nearbyVisible ?? true
    }
  }
}
