import { join } from 'node:path';
import { writeFileSync } from 'node:fs';
import { networkInterfaces } from 'node:os';
import { C as error, O as fail } from '../../../chunks/utils.js-mIi_c4Oz.js';
import QRCode from 'qrcode';
import { a as hasRole } from '../../../chunks/auth.js-D502gejJ.js';
import { D as DATA_DIR } from '../../../chunks/db.js-le-jjQPv.js';

function lanIp() {
  const nets = networkInterfaces();
  for (const name of Object.keys(nets)) {
    for (const net of nets[name] ?? []) {
      if (net.family === "IPv4" && !net.internal) return net.address;
    }
  }
  return "127.0.0.1";
}
const load = async ({ locals }) => {
  if (!hasRole(locals.user, "admin")) throw error(403, "Solo administración.");
  const mode = (process.env.EDUMIND_MODE ?? "local").toLowerCase() === "red" ? "red" : "local";
  const supervised = process.env.EDUMIND_SUPERVISED === "1";
  const port = process.env.PORT ?? "4600";
  const scheme = mode === "red" ? "https" : "http";
  const ip = lanIp();
  const networkUrl = mode === "red" ? `https://${ip}:${port}` : null;
  const localUrl = `${scheme}://localhost:${port}`;
  const qrSvg = networkUrl ? await QRCode.toString(networkUrl, { type: "svg", margin: 1, errorCorrectionLevel: "M" }) : null;
  return { mode, supervised, port, ip, networkUrl, localUrl, qrSvg };
};
function scheduleExit(code) {
  setTimeout(() => process.exit(code), 700);
}
const actions = {
  setMode: async ({ request, locals }) => {
    if (!hasRole(locals.user, "admin")) throw error(403, "Solo administración.");
    if (process.env.EDUMIND_SUPERVISED !== "1") {
      return fail(400, { error: "El cambio de modo solo está disponible en la app instalada." });
    }
    const mode = String((await request.formData()).get("mode") ?? "").toLowerCase();
    if (mode !== "local" && mode !== "red") return fail(400, { error: "Modo no válido." });
    writeFileSync(join(DATA_DIR, "mode.txt"), mode);
    const port = process.env.PORT ?? "4600";
    const url = mode === "red" ? `https://${lanIp()}:${port}` : `http://127.0.0.1:${port}`;
    scheduleExit(75);
    return { restarting: true, mode, url };
  },
  shutdown: async ({ locals }) => {
    if (!hasRole(locals.user, "admin")) throw error(403, "Solo administración.");
    if (process.env.EDUMIND_SUPERVISED !== "1") {
      return fail(400, { error: "Apagar solo está disponible en la app instalada." });
    }
    scheduleExit(0);
    return { shuttingDown: true };
  }
};

var _page_server_ts = /*#__PURE__*/Object.freeze({
  __proto__: null,
  actions: actions,
  load: load
});

export { _page_server_ts as _ };
//# sourceMappingURL=_page.server.ts.js-9rme86ZG.js.map
