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

####################################################################
# Koro ERP — ERP Installer (Linux / macOS)
#
# What this script does:
#   1. Checks prerequisites (docker, docker compose, openssl)
#   2. Asks about your database setup (bundled or external)
#   3. Generates RSA keys for JWT + licence signing
#   4. Generates secrets (DB password and JWT key)
#   5. Creates .env from your answers
#   6. Runs database schema initialization container
#   7. Pulls Docker images and starts everything
#
# Usage:
#   chmod +x install.sh
#   ./install.sh              # interactive
#   ./install.sh --defaults   # skip prompts, use bundled DB
#   ./install.sh --skip-db-init   # skip SQL dump initializer container
#
# After install, open the URL printed at the end → Setup Wizard
####################################################################

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# ── Flags ────────────────────────────────────────────────────────
AUTO_MODE=false
SKIP_DB_INIT=false

if [[ "${KORO_SKIP_DB_INIT:-}" =~ ^(1|true|TRUE|yes|YES|y|Y)$ ]]; then
  SKIP_DB_INIT=true
fi

for arg in "$@"; do
  case "$arg" in
    --defaults|-y)
      AUTO_MODE=true
      ;;
    --skip-db-init)
      SKIP_DB_INIT=true
      ;;
  esac
done

# ── Colors ───────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'

info()  { echo -e "${BLUE}[INFO]${NC}  $*"; }
ok()    { echo -e "${GREEN}  [OK]${NC}  $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
fail()  { echo -e "${RED}[FAIL]${NC}  $*"; exit 1; }
ask()   { echo -en "${CYAN}   [?]${NC}  $* "; }

# ── Banner ───────────────────────────────────────────────────────
echo ""
echo -e "${BOLD}${BLUE}╔═══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}${BLUE}║                   Koro ERP Installer                    ║${NC}"
echo -e "${BOLD}${BLUE}╚═══════════════════════════════════════════════════════════╝${NC}"
echo ""

# ═════════════════════════════════════════════════════════════════
# 1. Prerequisites — auto-install Docker if missing
# ═════════════════════════════════════════════════════════════════
info "Checking prerequisites..."

install_docker() {
  info "Docker not found — installing automatically..."

  # Detect OS
  if [ -f /etc/os-release ]; then
    . /etc/os-release
    DISTRO="$ID"
  elif [[ "$OSTYPE" == "darwin"* ]]; then
    DISTRO="macos"
  else
    DISTRO="unknown"
  fi

  case "$DISTRO" in
    ubuntu|debian|pop|linuxmint|elementary)
      info "Detected $DISTRO — installing Docker via apt..."
      sudo apt-get update -qq
      sudo apt-get install -y -qq ca-certificates curl gnupg lsb-release
      sudo install -m 0755 -d /etc/apt/keyrings
      curl -fsSL "https://download.docker.com/linux/$DISTRO/gpg" | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg 2>/dev/null || \
        curl -fsSL "https://download.docker.com/linux/ubuntu/gpg" | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg 2>/dev/null
      sudo chmod a+r /etc/apt/keyrings/docker.gpg
      echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/${DISTRO:-ubuntu} $(lsb_release -cs 2>/dev/null || echo noble) stable" | \
        sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
      sudo apt-get update -qq
      sudo apt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
      ;;
    fedora)
      info "Detected Fedora — installing Docker via dnf..."
      sudo dnf -y install dnf-plugins-core
      sudo dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo
      sudo dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
      ;;
    centos|rhel|rocky|almalinux)
      info "Detected $DISTRO — installing Docker via yum..."
      sudo yum install -y yum-utils
      sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
      sudo yum install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
      ;;
    amzn)
      info "Detected Amazon Linux — installing Docker..."
      sudo yum install -y docker
      sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" \
        -o /usr/local/bin/docker-compose
      sudo chmod +x /usr/local/bin/docker-compose
      ;;
    arch|manjaro)
      info "Detected $DISTRO — installing Docker via pacman..."
      sudo pacman -Sy --noconfirm docker docker-compose
      ;;
    opensuse*|sles)
      info "Detected $DISTRO — installing Docker via zypper..."
      sudo zypper install -y docker docker-compose
      ;;
    macos)
      if command -v brew >/dev/null 2>&1; then
        info "Installing Docker via Homebrew..."
        brew install --cask docker
        echo ""
        warn "Docker Desktop installed. Please open it from Applications"
        warn "and wait for it to start, then re-run this installer."
        exit 0
      else
        fail "Install Docker Desktop manually from https://www.docker.com/products/docker-desktop"
      fi
      ;;
    *)
      # Fallback: use Docker's convenience script
      info "Unknown distro — using Docker convenience script..."
      curl -fsSL https://get.docker.com | sudo sh
      ;;
  esac

  # Start and enable Docker
  if command -v systemctl >/dev/null 2>&1; then
    sudo systemctl start docker 2>/dev/null || true
    sudo systemctl enable docker 2>/dev/null || true
  elif command -v service >/dev/null 2>&1; then
    sudo service docker start 2>/dev/null || true
  fi

  # Add current user to docker group (avoids needing sudo for docker)
  if [ "$(id -u)" -ne 0 ] && ! groups | grep -q docker; then
    sudo usermod -aG docker "$USER" 2>/dev/null || true
    warn "Added $USER to docker group. You may need to log out and back in."
    warn "For now, the installer will use sudo for docker commands."
  fi

  # Verify installation
  if ! command -v docker >/dev/null 2>&1; then
    fail "Docker installation failed. Install manually from https://docs.docker.com/get-docker/"
  fi
  ok "Docker installed successfully"
}

install_openssl() {
  info "OpenSSL not found — installing..."
  if [ -f /etc/os-release ]; then
    . /etc/os-release
    case "$ID" in
      ubuntu|debian|pop|linuxmint) sudo apt-get install -y -qq openssl ;;
      fedora)                      sudo dnf install -y openssl ;;
      centos|rhel|rocky|almalinux) sudo yum install -y openssl ;;
      arch|manjaro)                sudo pacman -Sy --noconfirm openssl ;;
      opensuse*|sles)              sudo zypper install -y openssl ;;
      *)                           sudo apt-get install -y openssl 2>/dev/null || sudo yum install -y openssl 2>/dev/null ;;
    esac
  elif [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS ships with LibreSSL as 'openssl'
    command -v brew >/dev/null 2>&1 && brew install openssl
  fi
}

# ── Check / Install Docker ──────────────────────────────────────
if ! command -v docker >/dev/null 2>&1; then
  if [ "$AUTO_MODE" = true ]; then
    install_docker
  else
    warn "Docker is not installed."
    ask "Install Docker automatically? [Y/n]:"
    read -r install_choice
    if [[ "$install_choice" =~ ^[Nn] ]]; then
      fail "Docker is required. Install it from https://docs.docker.com/get-docker/"
    fi
    install_docker
  fi
fi

# ── Check / Install Docker Compose ──────────────────────────────
if ! docker compose version >/dev/null 2>&1; then
  info "Docker Compose V2 not found — installing plugin..."
  COMPOSE_VERSION=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
  COMPOSE_VERSION="${COMPOSE_VERSION:-v2.29.1}"
  sudo mkdir -p /usr/local/lib/docker/cli-plugins
  sudo curl -SL "https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" \
    -o /usr/local/lib/docker/cli-plugins/docker-compose
  sudo chmod +x /usr/local/lib/docker/cli-plugins/docker-compose
  docker compose version >/dev/null 2>&1 || fail "Docker Compose installation failed."
  ok "Docker Compose installed"
fi

# ── Check / Install OpenSSL ─────────────────────────────────────
if ! command -v openssl >/dev/null 2>&1; then
  install_openssl
  command -v openssl >/dev/null 2>&1 || fail "OpenSSL is required but could not be installed."
fi

ok "Docker $(docker --version | grep -oP 'Docker version \K[0-9.]+')"
ok "Docker Compose $(docker compose version --short)"
ok "OpenSSL available"

# ═════════════════════════════════════════════════════════════════
# 2. Database configuration
# ═════════════════════════════════════════════════════════════════
echo ""
USE_BUNDLED_DB="true"
NATIVE_PG="false"
DB_HOST="postgres"
DB_PORT="5432"
DB_USER="postgres"
DB_PASSWORD=""
DB_SSLMODE="disable"

install_native_postgres() {
  info "Installing PostgreSQL on this server..."

  if [ -f /etc/os-release ]; then
    . /etc/os-release
    DISTRO="$ID"
  elif [[ "$OSTYPE" == "darwin"* ]]; then
    DISTRO="macos"
  else
    DISTRO="unknown"
  fi

  case "$DISTRO" in
    ubuntu|debian|pop|linuxmint|elementary)
      sudo apt-get update -qq
      sudo apt-get install -y -qq postgresql postgresql-client
      ;;
    fedora)
      sudo dnf install -y postgresql-server postgresql
      sudo postgresql-setup --initdb 2>/dev/null || true
      ;;
    centos|rhel|rocky|almalinux)
      sudo yum install -y postgresql-server postgresql
      sudo postgresql-setup --initdb 2>/dev/null || true
      ;;
    arch|manjaro)
      sudo pacman -Sy --noconfirm postgresql
      sudo -u postgres initdb -D /var/lib/postgres/data 2>/dev/null || true
      ;;
    opensuse*|sles)
      sudo zypper install -y postgresql-server postgresql
      ;;
    macos)
      if command -v brew >/dev/null 2>&1; then
        brew install postgresql@16
        brew services start postgresql@16
      else
        fail "Install Homebrew first, or use Docker (option 1)"
      fi
      ;;
    *)
      fail "Cannot auto-install PostgreSQL on this OS. Use Docker (option 1) or install PostgreSQL manually (option 3)."
      ;;
  esac

  # Start and enable PostgreSQL
  if command -v systemctl >/dev/null 2>&1; then
    sudo systemctl start postgresql 2>/dev/null || true
    sudo systemctl enable postgresql 2>/dev/null || true
  elif command -v service >/dev/null 2>&1; then
    sudo service postgresql start 2>/dev/null || true
  fi

  # Wait a moment for PG to start
  sleep 3

  # Verify
  if ! command -v psql >/dev/null 2>&1; then
    fail "PostgreSQL installation failed. Install manually or use Docker (option 1)."
  fi
  ok "PostgreSQL installed"
}

configure_native_postgres() {
  info "Configuring PostgreSQL..."

  # Set the postgres user password
  sudo -u postgres psql -c "ALTER USER postgres PASSWORD '${DB_PASSWORD}';" 2>/dev/null || \
    psql -U postgres -c "ALTER USER postgres PASSWORD '${DB_PASSWORD}';" 2>/dev/null || true

  # Update pg_hba.conf to allow password auth from localhost
  PG_HBA=$(sudo -u postgres psql -t -c "SHOW hba_file;" 2>/dev/null | tr -d ' ' || echo "")
  if [ -n "$PG_HBA" ] && [ -f "$PG_HBA" ]; then
    # Ensure md5/scram-sha-256 auth for local connections
    if grep -q "^local.*all.*all.*peer" "$PG_HBA" 2>/dev/null; then
      sudo sed -i 's/^local\s*all\s*all\s*peer/local   all             all                                     md5/' "$PG_HBA" 2>/dev/null || true
    fi
    if grep -q "^host.*all.*all.*127.0.0.1.*ident" "$PG_HBA" 2>/dev/null; then
      sudo sed -i 's|^host\s*all\s*all\s*127.0.0.1/32\s*ident|host    all             all             127.0.0.1/32            md5|' "$PG_HBA" 2>/dev/null || true
    fi
    # Reload config
    sudo -u postgres psql -c "SELECT pg_reload_conf();" 2>/dev/null || \
      sudo systemctl reload postgresql 2>/dev/null || true
  fi

  ok "PostgreSQL configured"
}

run_db_initializer() {
  local init_host="$DB_HOST"
  local add_host_args=()
  local max_attempts=20
  local attempt

  if [ "$init_host" = "postgres" ] || [ "$init_host" = "127.0.0.1" ] || [ "$init_host" = "localhost" ]; then
    init_host="host.docker.internal"
    add_host_args+=(--add-host=host.docker.internal:host-gateway)
  fi

  info "Running SQL dump initializer (korobosta/koro-db-init:latest)..."

  for attempt in $(seq 1 "$max_attempts"); do
    if docker run --rm \
      "${add_host_args[@]}" \
      -e DB_HOST="$init_host" \
      -e DB_PORT="$DB_PORT" \
      -e DB_USER="$DB_USER" \
      -e DB_PASSWORD="$DB_PASSWORD" \
      -e PGSSLMODE="$DB_SSLMODE" \
      korobosta/koro-db-init:latest; then
      ok "Database schemas initialized"
      return 0
    fi

    if [ "$attempt" -lt "$max_attempts" ]; then
      warn "DB initializer attempt ${attempt}/${max_attempts} failed; retrying in 3s..."
      sleep 3
    fi
  done

  fail "Database initializer failed after ${max_attempts} attempts. Check DB credentials/network and rerun."
}

if [ "$AUTO_MODE" = false ]; then
  info "Database setup"
  echo ""
  echo -e "  ${BOLD}1)${NC} Dockerised PostgreSQL (included in Docker — recommended)"
  echo -e "  ${BOLD}2)${NC} Install PostgreSQL natively on this server"
  echo -e "  ${BOLD}3)${NC} External PostgreSQL (your own server / managed service)"
  echo ""
  ask "Choose [1/2/3] (default: 1):"
  read -r db_choice
  db_choice="${db_choice:-1}"

  if [ "$db_choice" = "1" ] || [ "$db_choice" = "" ]; then
    echo ""
    echo -e "  ${YELLOW}┌─────────────────────────────────────────────────────────┐${NC}"
    echo -e "  ${YELLOW}│  NOTE: Dockerised PostgreSQL stores data in a Docker   │${NC}"
    echo -e "  ${YELLOW}│  volume (pgdata). Your data is safe across restarts     │${NC}"
    echo -e "  ${YELLOW}│  and upgrades. However, please be aware:               │${NC}"
    echo -e "  ${YELLOW}│                                                        │${NC}"
    echo -e "  ${YELLOW}│  • NEVER run: docker compose down -v  (deletes data!)  │${NC}"
    echo -e "  ${YELLOW}│  • Set up regular backups (pg_dump or volume snapshots) │${NC}"
    echo -e "  ${YELLOW}│  • For large-scale production, consider native or       │${NC}"
    echo -e "  ${YELLOW}│    managed PostgreSQL (options 2 or 3) instead          │${NC}"
    echo -e "  ${YELLOW}└─────────────────────────────────────────────────────────┘${NC}"
    echo ""
    ask "Continue with Dockerised PostgreSQL? [Y/n]:"
    read -r confirm_docker_db
    if [[ "$confirm_docker_db" =~ ^[Nn] ]]; then
      fail "Installation cancelled. Re-run and choose option 2 or 3."
    fi

  elif [ "$db_choice" = "2" ]; then
    USE_BUNDLED_DB="false"
    NATIVE_PG="true"
    DB_HOST="127.0.0.1"

    ask "Database password for postgres user:"
    read -rs DB_PASSWORD
    echo ""
    if [ -z "$DB_PASSWORD" ]; then
      DB_PASSWORD="$(openssl rand -base64 24 | tr -d '\n')"
      info "Auto-generated password: $DB_PASSWORD"
    fi

    ask "Database port (default: 5432):"
    read -r DB_PORT
    DB_PORT="${DB_PORT:-5432}"

    # Install PostgreSQL if not already present
    if ! command -v psql >/dev/null 2>&1; then
      install_native_postgres
    else
      ok "PostgreSQL already installed ($(psql --version | head -1))"
    fi

  elif [ "$db_choice" = "3" ]; then
    USE_BUNDLED_DB="false"
    echo ""
    ask "Database host (IP or hostname):"
    read -r DB_HOST
    [ -z "$DB_HOST" ] && fail "Database host is required"

    ask "Database port (default: 5432):"
    read -r DB_PORT
    DB_PORT="${DB_PORT:-5432}"

    ask "Database user (default: postgres):"
    read -r DB_USER
    DB_USER="${DB_USER:-postgres}"

    ask "Database password:"
    read -rs DB_PASSWORD
    echo ""
    [ -z "$DB_PASSWORD" ] && fail "Database password is required"

    ask "SSL mode [disable/require] (default: disable):"
    read -r DB_SSLMODE
    DB_SSLMODE="${DB_SSLMODE:-disable}"

  fi
fi

# Generate password for bundled DB if needed
if [ "$USE_BUNDLED_DB" = "true" ] && [ -z "$DB_PASSWORD" ]; then
  DB_PASSWORD="$(openssl rand -base64 24 | tr -d '\n')"
fi

# ── SaaS enrollment ─────────────────────────────────────────────
ENROLLMENT_TOKEN="${ENROLLMENT_TOKEN:-}"
if [ "$AUTO_MODE" = false ] && [ -z "$ENROLLMENT_TOKEN" ]; then
  echo ""
  info "Connected SaaS installation"
  echo "    Generate a one-time token in the Tenant Portal under ERP Installation."
  echo "    It expires after 15 minutes and can be used only once."
  echo "    Leave blank for an air-gapped or local-only installation."
  ask "Enrollment token:"
  read -r ENROLLMENT_TOKEN
fi

# ═════════════════════════════════════════════════════════════════
# 3. Port configuration
# ═════════════════════════════════════════════════════════════════
FRONTEND_PORT="10000"
GATEWAY_PORT="7009"
HTTP_PORT="80"
HTTPS_PORT="443"
TENANT_DOMAIN=""
API_SUBDOMAIN="api"
ACME_EMAIL=""

if [ "$AUTO_MODE" = false ]; then
  echo ""
  info "Port configuration"
  info "Web UI HTTP fallback uses port ${FRONTEND_PORT} automatically."

  info "API gateway uses port ${GATEWAY_PORT} automatically."

  echo ""
  info "Domain / TLS configuration"
  echo "    Enter the apex domain the deployment will live under."
  echo "    Caddy pulls Let's Encrypt certificates for erp.<domain>,"
  echo "    api.<domain>, pos.<domain>, etc. automatically once DNS"
  echo "    points at this server.  Leave blank for a bare-IP / smoke-test"
  echo "    install — you'll only get plain HTTP on port ${FRONTEND_PORT}."
  ask "Tenant apex domain (e.g. acmecorp.com, empty = skip TLS):"
  read -r td
  TENANT_DOMAIN="${td:-}"

  if [ -n "$TENANT_DOMAIN" ]; then
    ask "API subdomain (default: api):"
    read -r as
    API_SUBDOMAIN="${as:-api}"

    ask "Contact email for Let's Encrypt renewal notices:"
    read -r ae
    ACME_EMAIL="${ae:-admin@${TENANT_DOMAIN}}"

    echo ""
    info "DNS records required before TLS can be issued"
    echo "    ${API_SUBDOMAIN}.${TENANT_DOMAIN}"
    if [[ "${KORO_INSTALL_APPS:-false}" == "true" ]]; then
      echo "    business.${TENANT_DOMAIN}"
      echo "    pos.${TENANT_DOMAIN}"
      echo "    staff.${TENANT_DOMAIN}"
      echo "    hub.${TENANT_DOMAIN}"
      echo "    school.${TENANT_DOMAIN}"
      echo "    merchants.${TENANT_DOMAIN}"
      echo "    partners.${TENANT_DOMAIN}"
    fi
    echo "    Point each selected hostname to this server before continuing."
    ask "Have these DNS records been configured? [Y/n]:"
    read -r dns_ready
    if [[ "$dns_ready" =~ ^[Nn] ]]; then
      warn "TLS issuance may fail until DNS records resolve to this server."
    fi
  fi


fi

# ═════════════════════════════════════════════════════════════════
# 4. Generate RSA keys
# ═════════════════════════════════════════════════════════════════
echo ""
if [ ! -d "keys" ] || [ ! -f "keys/private.pem" ]; then
  info "Generating RSA key pair for JWT signing..."
  mkdir -p keys
  openssl genpkey -algorithm RSA -out keys/private.pem -pkeyopt rsa_keygen_bits:2048 2>/dev/null
  openssl rsa -pubout -in keys/private.pem -out keys/public.pem 2>/dev/null
  chmod 600 keys/private.pem
  chmod 644 keys/public.pem
  ok "JWT keys generated"
else
  ok "JWT keys already exist"
fi

if [ ! -f "keys/licence_public.pem" ]; then
  info "Writing KoroERP licence verification public key..."
  cat > keys/licence_public.pem << 'LICENCE_PUB_KEY'
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1qJEO/nQpRSQoYHWMSm7
U7zrzpGfr2/kYvjREwHBGf6n2nBH5OiAdE+I+bhBWvrRL74o7e1w8FIPsdJ9vAtS
3CH1xiYeCBgQcpxVHgwV0EZ1M38Tyxye8IGiLSy/FPlqT5fDGxDYTSbRPpvTasB5
eK58qtj7cbwEkXj39YoRxk5f56f2+bsbA6JAZ96U/fdYUxKsZ3Z6OhiFIRJ0hN1P
Z1MswqEUqHnkREMLeeXgxY3jqL20Ns3t+9SpN4xVWXkrINJkimDkzo+ZywsLUVN3
zacv9o7HPt23/lWNqHSVAAruNzQtLbJdcqlvTY0PGDJRYHSab+R2z+9fO4kmqdz2
/wIDAQAB
-----END PUBLIC KEY-----
LICENCE_PUB_KEY
  chmod 644 keys/licence_public.pem
  ok "Licence public key written"
fi

# ═════════════════════════════════════════════════════════════════
# 5. Generate secrets + write .env
# ═════════════════════════════════════════════════════════════════
gen_secret() { openssl rand -base64 "$1" | tr -d '\n'; }

if [ ! -f ".env" ]; then
  info "Generating configuration..."
  JWT_SECRET_KEY="$(gen_secret 32)"
  ERP_SERVICE_TOKEN="$(gen_secret 32)"
	DATA_ENCRYPTION_KEY="$(gen_secret 32)"
  PLATFORM_API_URL="${PLATFORM_API_URL:-https://platform-api.koroworks.com}"
  ENROLLMENT_TOKEN="${ENROLLMENT_TOKEN:-}"
  DOCUMENTS_ENCRYPTION_KEY="$(gen_secret 32)"
  MARKETING_ENCRYPTION_KEY="$(gen_secret 32)"
  MONITOR_ENCRYPTION_KEY="$(gen_secret 32)"
  NOTIFICATIONS_ENCRYPTION_KEY="$(gen_secret 32)"
  PAYMENT_GATEWAY_ENCRYPTION_KEY="$(gen_secret 32)"

  cat > .env <<EOF
# Auto-generated by install.sh on $(date -u +"%Y-%m-%d %H:%M:%S UTC")
# Do NOT commit this file to version control.

# ─── Database ────────────────────────────────────────────────────
DB_HOST=${DB_HOST}
DB_PORT=${DB_PORT}
DB_USER=${DB_USER}
DB_PASSWORD=${DB_PASSWORD}
DB_SSLMODE=${DB_SSLMODE}

# ─── Secrets ─────────────────────────────────────────────────────
if [[ "${INSTALL_MTLS_REQUIRED:-false}" == "true" ]]; then
  INSTALL_CLIENT_CERT="${INSTALL_CLIENT_CERT:-/root/internal/config/keys/install-client.pem}"
  INSTALL_CLIENT_KEY="${INSTALL_CLIENT_KEY:-/root/internal/config/keys/install-client-key.pem}"
else
  INSTALL_CLIENT_CERT="${INSTALL_CLIENT_CERT:-}"
  INSTALL_CLIENT_KEY="${INSTALL_CLIENT_KEY:-}"
fi
INSTALL_CA_BUNDLE="${INSTALL_CA_BUNDLE:-}"
JWT_SECRET_KEY=${JWT_SECRET_KEY}
REGISTRY=${REGISTRY:-korobosta}
ERP_SERVICE_TOKEN=${ERP_SERVICE_TOKEN}
DATA_ENCRYPTION_KEY=${DATA_ENCRYPTION_KEY}
PLATFORM_API_URL=${PLATFORM_API_URL}
MARKETING_BASE_URL=${MARKETING_BASE_URL:-https://koroworks.com}
ENROLLMENT_TOKEN=${ENROLLMENT_TOKEN}
INSTALL_MTLS_REQUIRED=${INSTALL_MTLS_REQUIRED:-false}
INSTALL_CLIENT_CERT=${INSTALL_CLIENT_CERT}
INSTALL_CLIENT_KEY=${INSTALL_CLIENT_KEY}
INSTALL_CA_BUNDLE=${INSTALL_CA_BUNDLE}

# ─── Per-Service Encryption Keys (AES-256) ───────────────────────
DOCUMENTS_ENCRYPTION_KEY=${DOCUMENTS_ENCRYPTION_KEY}
MARKETING_ENCRYPTION_KEY=${MARKETING_ENCRYPTION_KEY}
MONITOR_ENCRYPTION_KEY=${MONITOR_ENCRYPTION_KEY}
NOTIFICATIONS_ENCRYPTION_KEY=${NOTIFICATIONS_ENCRYPTION_KEY}
PAYMENT_GATEWAY_ENCRYPTION_KEY=${PAYMENT_GATEWAY_ENCRYPTION_KEY}

# ─── Ports ───────────────────────────────────────────────────────
HTTP_PORT=${HTTP_PORT}
HTTPS_PORT=${HTTPS_PORT}
FRONTEND_PORT=${FRONTEND_PORT}
GATEWAY_PORT=${GATEWAY_PORT}

# ─── Reverse proxy / TLS ──────────────────────────────────────
TENANT_DOMAIN=${TENANT_DOMAIN}
API_SUBDOMAIN=${API_SUBDOMAIN}
ACME_EMAIL=${ACME_EMAIL}
# Uncomment for airgapped / self-signed installs:
# CADDY_GLOBAL_EXTRA=local_certs

# ─── Networking ──────────────────────────────────────────────────
CORS_ALLOWED_ORIGINS=*

# ─── Docker images ───────────────────────────────────────────────
# REGISTRY=korobosta
# VERSION=latest
EOF

  chmod 600 .env
  ok ".env created"
else
  ok ".env already exists — not overwriting"
  # Source existing .env for the startup step
  set -a; source .env 2>/dev/null || true; set +a
fi

# ═════════════════════════════════════════════════════════════════
# 6. Pull images + Start
# ═════════════════════════════════════════════════════════════════
echo ""
info "Pulling Docker images (this may take a few minutes)..."
COMPOSE_PROFILES=""
if [ "$USE_BUNDLED_DB" = "true" ]; then
  COMPOSE_PROFILES="db"
fi

COMPOSE_CMD="docker compose -f docker-compose.yml"
if [ -n "$COMPOSE_PROFILES" ]; then
  COMPOSE_CMD="$COMPOSE_CMD --profile $COMPOSE_PROFILES"
fi

# If native PG was chosen, configure it now
if [ "$NATIVE_PG" = "true" ]; then
  configure_native_postgres
fi

$COMPOSE_CMD pull 2>/dev/null || warn "Some images may not be available yet"

echo ""
info "Starting Koro ERP..."
$COMPOSE_CMD up -d

if [ "$SKIP_DB_INIT" = "true" ]; then
  warn "Skipping database initializer (KORO_SKIP_DB_INIT/--skip-db-init enabled)."
else
  run_db_initializer
fi

# ═════════════════════════════════════════════════════════════════
# Done!
# ═════════════════════════════════════════════════════════════════
echo ""
echo -e "${GREEN}╔═══════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║           Koro ERP installed successfully!               ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════════════════╝${NC}"
echo ""
if [ -n "$TENANT_DOMAIN" ]; then
  if [[ "${KORO_INSTALL_APPS:-false}" == "true" ]]; then
    echo -e "  ${BOLD}Web UI:${NC}     ${BLUE}https://business.${TENANT_DOMAIN}${NC}"
  else
    echo -e "  ${BOLD}Web UI:${NC}     not installed (run the apps stage to deploy it)"
  fi
  echo -e "  ${BOLD}API:${NC}        ${BLUE}https://${API_SUBDOMAIN}.${TENANT_DOMAIN}${NC}"
  if [[ "${KORO_INSTALL_APPS:-false}" == "true" ]]; then
    echo -e "  ${BOLD}HTTP fb:${NC}    ${BLUE}http://localhost:${FRONTEND_PORT}${NC} (until DNS propagates)"
  fi
else
  if [[ "${KORO_INSTALL_APPS:-false}" == "true" ]]; then
    echo -e "  ${BOLD}Web UI:${NC}     ${BLUE}http://localhost:${FRONTEND_PORT}${NC}"
  else
    echo -e "  ${BOLD}Web UI:${NC}     not installed (run the apps stage to deploy it)"
  fi
  echo -e "  ${BOLD}API:${NC}        ${BLUE}http://localhost:${GATEWAY_PORT}${NC}"
fi
if [ "$USE_BUNDLED_DB" = "true" ]; then
  echo -e "  ${BOLD}Database:${NC}   Dockerised PostgreSQL (port ${DB_EXTERNAL_PORT:-5432})"
elif [ "$NATIVE_PG" = "true" ]; then
  echo -e "  ${BOLD}Database:${NC}   Native PostgreSQL on ${DB_HOST}:${DB_PORT}"
else
  echo -e "  ${BOLD}Database:${NC}   External — ${DB_HOST}:${DB_PORT}"
fi
echo ""
if [[ "${KORO_INSTALL_APPS:-false}" == "true" ]]; then
  echo -e "  Open the Web UI and complete the ${YELLOW}Setup Wizard${NC}"
  echo -e "  to create your first tenant and admin account."
else
  echo -e "  APIs are ready. Run the apps stage when you want the Web UI."
  echo -e "  Web apps can run here with the apps stage, or on another server using the same API URL."
fi
echo ""
echo -e "  ${RED}IMPORTANT:${NC} Keep .env and keys/ secure. Never commit them."
echo ""
