const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); // Schema für Eltern/Familie const userSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true, lowercase: true, trim: true }, password: { type: String, required: true, minlength: 6 }, familyName: { type: String, required: true, trim: true }, parentName: { type: String, required: true, trim: true }, role: { type: String, enum: ['parent', 'admin'], default: 'parent' }, isActive: { type: Boolean, default: true }, preferences: { notifications: { type: Boolean, default: true }, language: { type: String, default: 'de' }, theme: { type: String, enum: ['light', 'dark'], default: 'light' } }, createdAt: { type: Date, default: Date.now }, lastLogin: { type: Date, default: Date.now } }); // Passwort hashen vor dem Speichern userSchema.pre('save', async function(next) { // Nur hashen wenn Passwort geändert wurde if (!this.isModified('password')) return next(); try { // Passwort hashen const salt = await bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); next(); } catch (error) { next(error); } }); // Methode zum Passwort-Vergleich userSchema.methods.comparePassword = async function(candidatePassword) { return await bcrypt.compare(candidatePassword, this.password); }; // Virtuelle Eigenschaft für Kinder-Anzahl userSchema.virtual('childrenCount', { ref: 'Child', localField: '_id', foreignField: 'parent', count: true }); // JSON-Ausgabe anpassen (Passwort ausblenden) userSchema.methods.toJSON = function() { const user = this.toObject(); delete user.password; return user; }; module.exports = mongoose.model('User', userSchema);