// Generiert selbstsignierte Zertifikate bei npm install
import fs from 'fs';
import path from 'path';
import selfsigned from 'selfsigned';

const CERT_DIR = path.resolve('certs');
const KEY_PATH = path.join(CERT_DIR, 'localhost.key');
const CRT_PATH = path.join(CERT_DIR, 'localhost.crt');

function ensureDir(p) {
  if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true });
}

function generateIfMissing() {
  ensureDir(CERT_DIR);
  const host = process.env.HTTPS_HOST || 'localhost';
  const days = parseInt(process.env.HTTPS_CERT_DAYS || '3650', 10);

  const needKey = !fs.existsSync(KEY_PATH);
  const needCrt = !fs.existsSync(CRT_PATH);

  if (!needKey && !needCrt) {
    console.log(`[certs] Zertifikate existieren bereits in ${CERT_DIR}`);
    return;
  }

  console.log(`[certs] Erzeuge selbstsigniertes Zertifikat für CN=${host}, ${days} Tage gültig...`);
  const attrs = [{ name: 'commonName', value: host }];
  const pems = selfsigned.generate(attrs, {
    keySize: 2048,
    days,
    algorithm: 'sha256',
    extensions: [
      { name: 'basicConstraints', cA: true },
      { name: 'keyUsage', keyCertSign: true, digitalSignature: true, nonRepudiation: true, keyEncipherment: true },
      { name: 'extKeyUsage', serverAuth: true, clientAuth: true },
      { name: 'subjectAltName', altNames: [ { type: 2, value: host }, { type: 7, ip: '127.0.0.1' } ] }
    ]
  });

  fs.writeFileSync(KEY_PATH, pems.private, { mode: 0o600 });
  fs.writeFileSync(CRT_PATH, pems.cert, { mode: 0o644 });

  const readme = `Diese Zertifikate sind nur für lokale Entwicklung gedacht.

` +
    `Dateien:
- ${KEY_PATH}
- ${CRT_PATH}

` +
    `Nicht committen! Siehe .gitignore.`;
  fs.writeFileSync(path.join(CERT_DIR, 'README.txt'), readme);

  console.log(`[certs] Zertifikate erzeugt unter ${CERT_DIR}`);
}

try {
  generateIfMissing();
} catch (err) {
  console.error('[certs] Fehler beim Erzeugen der Zertifikate:', err?.message || err);
  process.exit(0); // nicht als harter Fehler werten
}
