import { existsSync, readFileSync } from "node:fs";
import { createServer } from "node:http";
import path from "node:path";
import { fileURLToPath } from "node:url";

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const certPath = process.env.IOS_CERT_PATH ?? path.join(root, "certs/inventory2026-local-ca.cer");
const host = process.env.IOS_CERT_HOST ?? "0.0.0.0";
const port = Number(process.env.IOS_CERT_PORT ?? 3002);

if (!existsSync(certPath)) {
  console.error(`Missing certificate file: ${certPath}`);
  process.exit(1);
}

function mobileConfig() {
  const certBase64 = readFileSync(certPath).toString("base64");
  return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>PayloadContent</key>
  <array>
    <dict>
      <key>PayloadCertificateFileName</key>
      <string>SSS Inventory Local CA.cer</string>
      <key>PayloadContent</key>
      <data>${certBase64}</data>
      <key>PayloadDescription</key>
      <string>Installs the local SSS Inventory certificate authority for HTTPS testing on your private network.</string>
      <key>PayloadDisplayName</key>
      <string>SSS Inventory Local CA</string>
      <key>PayloadIdentifier</key>
      <string>com.inventory2026.local.ca</string>
      <key>PayloadType</key>
      <string>com.apple.security.root</string>
      <key>PayloadUUID</key>
      <string>96B1D15F-B9F6-4C7E-A4D5-D85AE9FCD12E</string>
      <key>PayloadVersion</key>
      <integer>1</integer>
    </dict>
  </array>
  <key>PayloadDescription</key>
  <string>SSS Inventory local HTTPS certificate profile.</string>
  <key>PayloadDisplayName</key>
  <string>SSS Inventory Local HTTPS</string>
  <key>PayloadIdentifier</key>
  <string>com.inventory2026.local.https</string>
  <key>PayloadOrganization</key>
  <string>SSS Inventory</string>
  <key>PayloadRemovalDisallowed</key>
  <false/>
  <key>PayloadType</key>
  <string>Configuration</string>
  <key>PayloadUUID</key>
  <string>64D32A5A-CB95-4D0B-89AF-5984B31B23E7</string>
  <key>PayloadVersion</key>
  <integer>1</integer>
</dict>
</plist>`;
}

createServer((request, response) => {
  if (request.url === "/inventory2026-local-ca.mobileconfig") {
    response.writeHead(200, {
      "content-type": "application/x-apple-aspen-config",
      "content-disposition": "attachment; filename=inventory2026-local-ca.mobileconfig"
    });
    response.end(mobileConfig());
    return;
  }

  if (request.url === "/inventory2026-local-ca.cer") {
    response.writeHead(200, {
      "content-type": "application/x-x509-ca-cert",
      "content-disposition": "attachment; filename=inventory2026-local-ca.cer"
    });
    response.end(readFileSync(certPath));
    return;
  }

  response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
  response.end(`<!doctype html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Install SSS Inventory Certificate</title>
    <style>
      body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; margin: 32px; line-height: 1.4; }
      a { display: block; padding: 14px 16px; border-radius: 8px; background: #0f766e; color: white; text-decoration: none; font-weight: 700; text-align: center; }
      .note { margin-top: 18px; color: #334155; }
    </style>
  </head>
  <body>
    <h1>SSS Inventory Local HTTPS</h1>
    <a href="/inventory2026-local-ca.mobileconfig">Install iPad Certificate Profile</a>
    <p class="note">After download, open Settings, tap Profile Downloaded, install it, then enable full trust in Settings > General > About > Certificate Trust Settings.</p>
  </body>
</html>`);
}).listen(port, host, () => {
  console.log(`SSS Inventory iOS certificate helper listening at http://${host}:${port}`);
});
