#!/usr/bin/env bash
set -euo pipefail

# Generate self-signed TLS cert for local development
# Outputs: infra/compose/traefik/certs/local.crt and local.key

CERT_DIR="infra/compose/traefik/certs"
mkdir -p "$CERT_DIR"

CRT="$CERT_DIR/local.crt"
KEY="$CERT_DIR/local.key"

if [[ -f "$CRT" && -f "$KEY" ]]; then
  echo "✅ Dev TLS certificate already exists at $CERT_DIR"
  exit 0
fi

echo "🔐 Generating self-signed TLS certificate for local domains..."

SAN="DNS:localhost,IP:127.0.0.1,DNS:*.local.lan,DNS:auth.local.lan,DNS:grafana.local.lan,DNS:review.local.lan,DNS:api.local.lan,DNS:vault.local.lan,DNS:minio.local.lan,DNS:minio-api.local.lan,DNS:qdrant.local.lan,DNS:neo4j.local.lan,DNS:prometheus.local.lan,DNS:loki.local.lan,DNS:unleash.local.lan,DNS:traefik.local.lan"

openssl req -x509 -nodes -newkey rsa:2048 -sha256 -days 3650 \
  -subj "/CN=local" \
  -keyout "$KEY" \
  -out "$CRT" \
  -addext "subjectAltName=$SAN" >/dev/null 2>&1

echo "✅ Generated $CRT and $KEY"
