// Script: set-all-visibility-flags.mjs
// Setzt für alle Mitglieder in allen relevanten Dateien alle visibility-Flags auf true (inkl. Entschlüsselung)

import { readMembers, writeMembers } from './utils/members.js';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs/promises';

dotenv.config({ path: path.resolve(process.cwd(), '.env') });

const usersPath = path.resolve(process.cwd(), 'server/data/users.json');

async function updateVisibility(obj) {
  let changed = 0;
  if (Array.isArray(obj)) {
    for (const m of obj) {
      if (!m.visibility) m.visibility = {};
      if (m.visibility.showEmail !== true) { m.visibility.showEmail = true; changed++; }
      if (m.visibility.showPhone !== true) { m.visibility.showPhone = true; changed++; }
      if (m.visibility.showAddress !== true) { m.visibility.showAddress = true; changed++; }
      if (m.visibility.showBirthday !== true) { m.visibility.showBirthday = true; changed++; }
    }
  }
  return changed;
}

async function updateUsersFile() {
  let changed = 0;
  try {
    let raw = await fs.readFile(usersPath, 'utf8');
    let users;
    if (raw.trim().startsWith('v2:')) {
      // encrypted, try to use decryptObject from encryption.js
      const { decryptObject } = await import('./utils/encryption.js');
      const key = process.env.ENCRYPTION_KEY || 'local_development_encryption_key_change_in_production';
      users = decryptObject(raw, key);
    } else {
      users = JSON.parse(raw);
    }
    changed = await updateVisibility(users);
    // write back (encrypted if vorher encrypted)
    if (raw.trim().startsWith('v2:')) {
      const { encryptObject } = await import('./utils/encryption.js');
      const key = process.env.ENCRYPTION_KEY || 'local_development_encryption_key_change_in_production';
      const encrypted = encryptObject(users, key);
      await fs.writeFile(usersPath, encrypted, 'utf8');
    } else {
      await fs.writeFile(usersPath, JSON.stringify(users, null, 2), 'utf8');
    }
    return changed;
  } catch (e) {
    console.error('Fehler beim Bearbeiten von users.json:', e);
    return 0;
  }
}

async function main() {
  let changedMembers = 0;
  let changedUsers = 0;
  // members.json (manuelle Mitglieder)
  let members = await readMembers();
  changedMembers = await updateVisibility(members);
  if (changedMembers > 0) {
    await writeMembers(members);
  }
  // users.json (Login-System)
  changedUsers = await updateUsersFile();
  console.log(`members.json: ${changedMembers} Änderungen, users.json: ${changedUsers} Änderungen`);
}

main();
