import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { promises } from 'fs';
import path from 'path';
import { d as decryptObject, a as encryptObject } from './encryption.mjs';

const JWT_SECRET = process.env.JWT_SECRET || "harheimertc-secret-key-change-in-production";
const getDataPath = (filename) => {
  const cwd = process.cwd();
  if (cwd.endsWith(".output")) {
    return path.join(cwd, "../server/data", filename);
  }
  return path.join(cwd, "server/data", filename);
};
const USERS_FILE = getDataPath("users.json");
const SESSIONS_FILE = getDataPath("sessions.json");
function getEncryptionKey() {
  return process.env.ENCRYPTION_KEY || "default-key-change-in-production";
}
function isEncrypted(data) {
  try {
    const parsed = JSON.parse(data.trim());
    if (Array.isArray(parsed)) {
      return false;
    }
    if (typeof parsed === "object" && parsed !== null && !parsed.encryptedData) {
      return false;
    }
    return false;
  } catch (e) {
    return true;
  }
}
async function readUsers() {
  try {
    const data = await promises.readFile(USERS_FILE, "utf-8");
    const encrypted = isEncrypted(data);
    if (encrypted) {
      const encryptionKey = getEncryptionKey();
      try {
        return decryptObject(data, encryptionKey);
      } catch (decryptError) {
        console.error("Fehler beim Entschl\xFCsseln der Benutzerdaten:", decryptError);
        try {
          const plainData = JSON.parse(data);
          console.warn("Entschl\xFCsselung fehlgeschlagen, versuche als unverschl\xFCsseltes Format zu lesen");
          return plainData;
        } catch (parseError) {
          console.error("Konnte Benutzerdaten weder entschl\xFCsseln noch als JSON lesen");
          return [];
        }
      }
    } else {
      const users = JSON.parse(data);
      console.log("Migriere unverschl\xFCsselte Benutzerdaten zu verschl\xFCsselter Speicherung...");
      await writeUsers(users);
      return users;
    }
  } catch (error) {
    if (error.code === "ENOENT") {
      return [];
    }
    console.error("Fehler beim Lesen der Benutzerdaten:", error);
    return [];
  }
}
async function writeUsers(users) {
  try {
    const encryptionKey = getEncryptionKey();
    const encryptedData = encryptObject(users, encryptionKey);
    await promises.writeFile(USERS_FILE, encryptedData, "utf-8");
    return true;
  } catch (error) {
    console.error("Fehler beim Schreiben der Benutzerdaten:", error);
    return false;
  }
}
async function readSessions() {
  try {
    const data = await promises.readFile(SESSIONS_FILE, "utf-8");
    return JSON.parse(data);
  } catch (error) {
    console.error("Fehler beim Lesen der Sessions:", error);
    return [];
  }
}
async function writeSessions(sessions) {
  try {
    await promises.writeFile(SESSIONS_FILE, JSON.stringify(sessions, null, 2), "utf-8");
    return true;
  } catch (error) {
    console.error("Fehler beim Schreiben der Sessions:", error);
    return false;
  }
}
async function hashPassword(password) {
  const salt = await bcrypt.genSalt(10);
  return await bcrypt.hash(password, salt);
}
async function verifyPassword(password, hash) {
  return await bcrypt.compare(password, hash);
}
function generateToken(user) {
  return jwt.sign(
    {
      id: user.id,
      email: user.email,
      role: user.role
    },
    JWT_SECRET,
    { expiresIn: "7d" }
  );
}
function verifyToken(token) {
  try {
    return jwt.verify(token, JWT_SECRET);
  } catch (error) {
    return null;
  }
}
async function getUserById(id) {
  const users = await readUsers();
  return users.find((u) => u.id === id);
}
async function getUserFromToken(token) {
  const decoded = verifyToken(token);
  if (!decoded) return null;
  const users = await readUsers();
  return users.find((u) => u.id === decoded.id);
}
async function createSession(userId, token) {
  const sessions = await readSessions();
  const session = {
    id: Date.now().toString(),
    userId,
    token,
    createdAt: (/* @__PURE__ */ new Date()).toISOString(),
    expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString()
    // 7 days
  };
  sessions.push(session);
  await writeSessions(sessions);
  return session;
}
async function deleteSession(token) {
  const sessions = await readSessions();
  const filtered = sessions.filter((s) => s.token !== token);
  await writeSessions(filtered);
}

export { getUserFromToken as a, verifyToken as b, createSession as c, deleteSession as d, getUserById as e, generateToken as g, hashPassword as h, readUsers as r, verifyPassword as v, writeUsers as w };
//# sourceMappingURL=auth.mjs.map
