#!/usr/bin/env node
(async () => {
  try {
    const { readMembers } = await import('../server/utils/members.js')
    const auth = await import('../server/utils/auth.js')
    const { readUsers } = auth

    const manual = await readMembers()
    const users = await readUsers()

    // Build simple merged list similar to members.get
    const merged = []

    // Add manual members
    for (const m of manual) {
      const fullName = `${m.firstName || ''} ${m.lastName || ''}`.trim()
      const vis = m.visibility || {}
      const visibility = {
        showEmail: vis.showEmail === undefined ? false : Boolean(vis.showEmail),
        showPhone: vis.showPhone === undefined ? false : Boolean(vis.showPhone),
        showAddress: vis.showAddress === undefined ? false : Boolean(vis.showAddress)
      }
      merged.push({
        id: m.id || null,
        name: fullName || m.name || '(kein name)',
        email: m.email || '',
        phone: m.phone || '',
        address: m.address || '',
        source: 'manual',
        visibility,
        raw: m
      })
    }

    // Add registered users (default visibility: false unless stored)
    for (const u of users) {
      if (!u.active) continue
      const visibility = u.visibility || { showEmail: false, showPhone: false, showAddress: false }
      merged.push({
        id: u.id,
        name: u.name,
        email: u.email || '',
        phone: u.phone || '',
        address: u.address || '',
        source: 'login',
        visibility,
        raw: u
      })
    }

    merged.sort((a, b) => a.name.localeCompare(b.name))

    const viewers = [
      { label: 'unauthenticated', isPrivileged: false },
      { label: 'admin', isPrivileged: false },
      { label: 'vorstand', isPrivileged: true }
    ]

    for (const v of viewers) {
      console.log('\n=== Viewer:', v.label, ' (vorstand override:', v.isPrivileged, ') ===')
      for (const m of merged) {
        const hadEmail = !!m.email
        const hadPhone = !!m.phone
        const showEmail = v.isPrivileged || Boolean(m.visibility.showEmail)
        const showPhone = v.isPrivileged || Boolean(m.visibility.showPhone)
        const contactHidden = (!showEmail && hadEmail) || (!showPhone && hadPhone)
        console.log(`- ${m.name}`)
        console.log(`  source: ${m.source}  roles?: ${m.raw.roles || m.raw.role || ''}`)
        console.log(`  email: ${hadEmail ? (showEmail ? m.email : '<HIDDEN>') : '-'}`)
        console.log(`  phone: ${hadPhone ? (showPhone ? m.phone : '<HIDDEN>') : '-'}`)
        if (contactHidden) console.log('  -> contactHidden = true')
      }
    }

    process.exit(0)
  } catch (e) {
    console.error('ERROR', e)
    process.exit(2)
  }
})()
