import { d as defineEventHandler, g as getCookie, c as createError, r as readBody } from '../../nitro/nitro.mjs';
import { b as verifyToken, r as readUsers, v as verifyPassword, h as hashPassword, w as writeUsers } from '../../_/auth.mjs';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'node:fs';
import 'node:path';
import 'node:crypto';
import 'node:url';
import 'bcryptjs';
import 'jsonwebtoken';
import 'fs';
import 'path';
import '../../_/encryption.mjs';
import 'crypto';

const profile_put = defineEventHandler(async (event) => {
  try {
    const token = getCookie(event, "auth_token");
    if (!token) {
      throw createError({
        statusCode: 401,
        message: "Nicht authentifiziert."
      });
    }
    const decoded = verifyToken(token);
    if (!decoded) {
      throw createError({
        statusCode: 401,
        message: "Ung\xFCltiges Token."
      });
    }
    const body = await readBody(event);
    const { name, email, phone, currentPassword, newPassword } = body;
    if (!name || !email) {
      throw createError({
        statusCode: 400,
        message: "Name und E-Mail sind erforderlich."
      });
    }
    const users = await readUsers();
    const userIndex = users.findIndex((u) => u.id === decoded.id);
    if (userIndex === -1) {
      throw createError({
        statusCode: 404,
        message: "Benutzer nicht gefunden."
      });
    }
    const user = users[userIndex];
    if (email !== user.email) {
      const emailExists = users.some((u) => u.email === email && u.id !== user.id);
      if (emailExists) {
        throw createError({
          statusCode: 409,
          message: "Diese E-Mail-Adresse wird bereits verwendet."
        });
      }
    }
    user.name = name;
    user.email = email;
    user.phone = phone || "";
    if (currentPassword && newPassword) {
      const isValid = await verifyPassword(currentPassword, user.password);
      if (!isValid) {
        throw createError({
          statusCode: 401,
          message: "Aktuelles Passwort ist falsch."
        });
      }
      if (newPassword.length < 6) {
        throw createError({
          statusCode: 400,
          message: "Das neue Passwort muss mindestens 6 Zeichen lang sein."
        });
      }
      user.password = await hashPassword(newPassword);
    }
    await writeUsers(users);
    return {
      success: true,
      message: "Profil erfolgreich aktualisiert.",
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        phone: user.phone,
        role: user.role
      }
    };
  } catch (error) {
    console.error("Profil-Update-Fehler:", error);
    throw error;
  }
});

export { profile_put as default };
//# sourceMappingURL=profile.put.mjs.map
