#!/usr/bin/env node
import fs from 'node:fs';
import path from 'node:path';
import { execSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const certDir = path.join(root, '.local/plaza-tls');
const plazaHost = process.env.PLAZA_LOCAL_HOST ?? 'plaza.tkmind.cn';
const keyPath = path.join(certDir, `${plazaHost}.key.pem`);
const certPath = path.join(certDir, `${plazaHost}.cert.pem`);

export function ensurePlazaLocalTls() {
  if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
    return { keyPath, certPath, certDir };
  }

  fs.mkdirSync(certDir, { recursive: true });
  const openssl = `openssl req -x509 -newkey rsa:2048 -sha256 -days 825 -nodes \
    -keyout "${keyPath}" -out "${certPath}" \
    -subj "/CN=${plazaHost}" \
    -addext "subjectAltName=DNS:${plazaHost},DNS:localhost,IP:127.0.0.1"`;

  execSync(openssl, { stdio: 'inherit' });
  console.log(`已生成本地 TLS 证书：${certDir}`);
  console.log('浏览器首次访问 https://plaza.tkmind.cn 需信任该证书。');
  return { keyPath, certPath, certDir };
}

if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  ensurePlazaLocalTls();
}
