#!/usr/bin/env node
import arg from 'arg'

async function main() {
  const args = arg({
    '--email': String,
    '--showEmail': Boolean,
    '--showPhone': Boolean,
    '--showAddress': Boolean,
    '--target': String // 'members'|'users'|'both'
  })

  const email = args['--email']
  if (!email) {
    console.error('Usage: node scripts/set-visibility.js --email <email> [--showEmail] [--showPhone] [--showAddress] [--target both|members|users]')
    process.exit(2)
  }

  const showEmail = '--showEmail' in args ? Boolean(args['--showEmail']) : undefined
  const showPhone = '--showPhone' in args ? Boolean(args['--showPhone']) : undefined
  const showAddress = '--showAddress' in args ? Boolean(args['--showAddress']) : undefined
  const target = args['--target'] || 'both'

  const membersUtils = await import('../server/utils/members.js')
  const authUtils = await import('../server/utils/auth.js')

  if (target === 'both' || target === 'members') {
    const members = await membersUtils.readMembers()
    let changed = false
    for (const m of members) {
      if ((m.email || '').toLowerCase() === email.toLowerCase()) {
        m.visibility = m.visibility || {}
        if (showEmail !== undefined) m.visibility.showEmail = showEmail
        if (showPhone !== undefined) m.visibility.showPhone = showPhone
        if (showAddress !== undefined) m.visibility.showAddress = showAddress
        changed = true
        console.log('Updated manual member visibility for', email)
      }
    }
    if (changed) {
      await membersUtils.writeMembers(members)
      console.log('Wrote members.json')
    }
  }

  if (target === 'both' || target === 'users') {
    const users = await authUtils.readUsers()
    let changed = false
    for (const u of users) {
      if ((u.email || '').toLowerCase() === email.toLowerCase()) {
        u.visibility = u.visibility || {}
        if (showEmail !== undefined) u.visibility.showEmail = showEmail
        if (showPhone !== undefined) u.visibility.showPhone = showPhone
        if (showAddress !== undefined) u.visibility.showAddress = showAddress
        changed = true
        console.log('Updated user visibility for', email)
      }
    }
    if (changed) {
      await authUtils.writeUsers(users)
      console.log('Wrote users.json')
    }
  }
}

main().catch(e => {
  console.error(e)
  process.exit(1)
})
