/* eslint-disable @typescript-eslint/no-require-imports */
const fs = require("fs");
const path = require("path");

const requiredEnv = ["ADMIN_EMAIL", "ADMIN_PASSWORD", "ADMIN_SESSION_SECRET"];
const requiredDirs = [
  path.join(process.cwd(), "data"),
  path.join(process.cwd(), "public", "uploads", "images"),
  path.join(process.cwd(), ".next", "cache"),
];

function fail(message) {
  process.stderr.write(`[funktechnik-website] ${message}\n`);
  process.exit(1);
}

function ensureWritableDirectory(directory) {
  fs.mkdirSync(directory, { recursive: true });
  const probe = path.join(directory, `.write-check-${Date.now()}`);
  fs.writeFileSync(probe, "ok", "utf8");
  fs.rmSync(probe, { force: true });
}

const missingEnv = requiredEnv.filter((name) => !process.env[name]);
if (missingEnv.length > 0) {
  fail(`Start abgebrochen: fehlende Umgebungsvariablen: ${missingEnv.join(", ")}. Bitte .env anhand von .env.example konfigurieren.`);
}

try {
  for (const directory of requiredDirs) ensureWritableDirectory(directory);
} catch (error) {
  fail(`Start abgebrochen: Runtime-Verzeichnis ist nicht beschreibbar. Details: ${error instanceof Error ? error.message : "unbekannter Fehler"}`);
}

process.stdout.write(`[funktechnik-website] Runtime checks ok. Starting version ${process.env.NEXT_PUBLIC_APP_VERSION ?? "0.2.2"}.\n`);
require("./server.js");
