#!/bin/bash

# Generate TLS certificates for development
# This script creates self-signed certificates for local development only
# DO NOT use these certificates in production

set -e

# Create certs directory if it doesn't exist
mkdir -p certs

# Change to certs directory
cd certs

# Generate private key
echo "Generating private key..."
openssl genrsa -out key.pem 2048

# Generate certificate signing request
echo "Generating certificate signing request..."
openssl req -new -key key.pem -out cert.csr -subj "/C=US/ST=State/L=City/O=Organization/OU=OrgUnit/CN=localhost"

# Generate self-signed certificate
echo "Generating self-signed certificate..."
openssl x509 -req -days 365 -in cert.csr -signkey key.pem -out cert.pem

# Create certificate with Subject Alternative Names for localhost
echo "Creating certificate with SAN..."
cat > cert.conf <<EOF
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no

[req_distinguished_name]
C = US
ST = State
L = City
O = Organization
OU = OrgUnit
CN = localhost

[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
DNS.2 = 127.0.0.1
IP.1 = 127.0.0.1
IP.2 = ::1
EOF

# Generate new certificate with SAN
openssl req -new -x509 -key key.pem -out cert.pem -days 365 -config cert.conf -extensions v3_req

# Clean up
rm cert.csr cert.conf

echo "✅ TLS certificates generated successfully!"
echo "📁 Certificates saved to: $(pwd)"
echo "🔐 Certificate: cert.pem"
echo "🔑 Private key: key.pem"
echo ""
echo "⚠️  These are self-signed certificates for development only!"
echo "⚠️  Your browser will show security warnings - this is normal for self-signed certs"
echo ""
echo "To use HTTPS, set SERVER_PROTOCOL=https in your .env file"
echo "The certificate paths are already configured in .env.example"
