#!/bin/bash
# ============================================================
# Nexus Autoparts POS — Uninstaller
# Cleanly removes all Nexus POS components
# Usage: sudo bash /opt/nexus-pos/uninstall.sh
# ============================================================
set -uo pipefail

# ----- Colors & helpers -----
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

INSTALL_DIR="/opt/nexus-pos"
SERVICE_NAME="nexus-pos"
DB_USER="nexus"
DB_NAME="nexus_autoparts"

info()  { echo -e "${CYAN}[INFO]${NC}  $*"; }
ok()    { echo -e "${GREEN}[OK]${NC}    $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
err()   { echo -e "${RED}[ERROR]${NC} $*"; }

# Must be root
if [[ $EUID -ne 0 ]]; then
    err "This script must be run as root. Use: sudo bash uninstall.sh"
    exit 1
fi

echo ""
echo -e "${BOLD}${RED}"
echo "  ========================================"
echo "   Nexus Autoparts POS — Uninstaller"
echo "  ========================================"
echo -e "${NC}"
echo ""
echo -e "  ${YELLOW}WARNING: This will remove:${NC}"
echo "    - Nexus POS systemd service"
echo "    - Nginx site configuration"
echo "    - Application files at ${INSTALL_DIR}"
echo ""
echo -e "  ${BOLD}Database removal is optional (asked separately).${NC}"
echo ""
echo -en "  ${BOLD}${RED}Continue with uninstall? [y/N]: ${NC}"
read -r confirm
if [[ "${confirm,,}" != "y" ]]; then
    info "Uninstall cancelled."
    exit 0
fi

# ============================================================
# 1. STOP AND REMOVE SYSTEMD SERVICE
# ============================================================
echo ""
info "Stopping ${SERVICE_NAME} service..."
if systemctl is-active --quiet "${SERVICE_NAME}" 2>/dev/null; then
    systemctl stop "${SERVICE_NAME}" 2>/dev/null
    ok "Service stopped."
else
    info "Service was not running."
fi

if systemctl is-enabled --quiet "${SERVICE_NAME}" 2>/dev/null; then
    systemctl disable "${SERVICE_NAME}" 2>/dev/null
    ok "Service disabled."
fi

if [[ -f "/etc/systemd/system/${SERVICE_NAME}.service" ]]; then
    rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
    systemctl daemon-reload 2>/dev/null
    ok "Service file removed."
fi

# ============================================================
# 2. REMOVE NGINX CONFIGURATION
# ============================================================
info "Removing nginx configuration..."
if [[ -f /etc/nginx/sites-enabled/nexus-pos ]]; then
    rm -f /etc/nginx/sites-enabled/nexus-pos
fi
if [[ -f /etc/nginx/sites-available/nexus-pos ]]; then
    rm -f /etc/nginx/sites-available/nexus-pos
fi
if command -v nginx &>/dev/null; then
    # Restore default site if it exists
    if [[ -f /etc/nginx/sites-available/default ]]; then
        ln -sf /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default 2>/dev/null || true
    fi
    nginx -t &>/dev/null && systemctl reload nginx 2>/dev/null
    ok "Nginx configuration removed."
fi

# ============================================================
# 3. REMOVE APPLICATION FILES
# ============================================================
info "Removing application files..."
if [[ -d "${INSTALL_DIR}" ]]; then
    rm -rf "${INSTALL_DIR}"
    ok "Removed ${INSTALL_DIR}"
else
    info "${INSTALL_DIR} not found (already removed?)."
fi

# ============================================================
# 4. DATABASE REMOVAL (OPTIONAL)
# ============================================================
echo ""
echo -e "  ${BOLD}${YELLOW}Database removal${NC}"
echo "  This will drop ALL tenant databases, the master database,"
echo "  and the PostgreSQL user. All data will be permanently lost."
echo ""
echo -en "  ${BOLD}${RED}Remove databases and PostgreSQL user? [y/N]: ${NC}"
read -r drop_db
if [[ "${drop_db,,}" == "y" ]]; then
    echo -en "  ${BOLD}${RED}Type 'DELETE' to confirm: ${NC}"
    read -r final_confirm
    if [[ "$final_confirm" == "DELETE" ]]; then
        info "Dropping databases..."

        # Get list of tenant databases
        TENANT_DBS=$(sudo -u postgres psql -tAc "SELECT db_name FROM tenants" "${DB_NAME}" 2>/dev/null || echo "")
        TEMPLATE_DB=$(sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='tenant_template'" 2>/dev/null || echo "")

        # Drop tenant databases
        if [[ -n "$TENANT_DBS" ]]; then
            while IFS= read -r tdb; do
                if [[ -n "$tdb" ]]; then
                    sudo -u postgres psql -c "DROP DATABASE IF EXISTS \"${tdb}\";" 2>/dev/null
                    ok "Dropped tenant database: ${tdb}"
                fi
            done <<< "$TENANT_DBS"
        fi

        # Drop template database
        if [[ -n "$TEMPLATE_DB" ]]; then
            sudo -u postgres psql -c "DROP DATABASE IF EXISTS tenant_template;" 2>/dev/null
            ok "Dropped template database."
        fi

        # Drop master database
        sudo -u postgres psql -c "DROP DATABASE IF EXISTS ${DB_NAME};" 2>/dev/null
        ok "Dropped master database: ${DB_NAME}"

        # Drop user
        sudo -u postgres psql -c "DROP USER IF EXISTS ${DB_USER};" 2>/dev/null
        ok "Dropped PostgreSQL user: ${DB_USER}"
    else
        warn "Database removal cancelled (confirmation did not match)."
    fi
else
    info "Databases preserved. You can remove them manually later."
    echo "    sudo -u postgres psql -c \"DROP DATABASE ${DB_NAME};\""
    echo "    sudo -u postgres psql -c \"DROP USER ${DB_USER};\""
fi

# ============================================================
# 5. REMOVE LOG FILE
# ============================================================
if [[ -f /var/log/nexus-pos-install.log ]]; then
    rm -f /var/log/nexus-pos-install.log
    ok "Install log removed."
fi

# ============================================================
# DONE
# ============================================================
echo ""
echo -e "${BOLD}${GREEN}"
echo "  ========================================"
echo "   Uninstall Complete"
echo "  ========================================"
echo -e "${NC}"
echo ""
echo -e "  ${BOLD}Removed:${NC}"
echo "    - Systemd service (${SERVICE_NAME})"
echo "    - Nginx site configuration"
echo "    - Application files (${INSTALL_DIR})"
if [[ "${drop_db,,}" == "y" && "$final_confirm" == "DELETE" ]]; then
    echo "    - All databases and PostgreSQL user"
else
    echo -e "    - Databases: ${YELLOW}NOT removed${NC} (kept by user request)"
fi
echo ""
echo "  Note: System packages (python3, postgresql, nginx, git)"
echo "  were NOT removed. Remove them manually if desired:"
echo "    apt-get remove --purge postgresql nginx"
echo ""
