#!/usr/bin/env bash
# =============================================================
#  Pay2X - Easy Setup (for SSH / cPanel Terminal users)
#  Run this ONE command after uploading the project:
#      bash setup.sh
#  It installs everything, prepares the database and builds.
# =============================================================
set -e

GREEN='\033[0;32m'; CYAN='\033[0;36m'; YELLOW='\033[1;33m'; BOLD='\033[1m'; NC='\033[0m'

echo -e "${BOLD}============================================================${NC}"
echo -e "${BOLD}            Pay2X - Easy Setup${NC}"
echo -e "${BOLD}============================================================${NC}"

# 1. Make sure .env exists
if [ ! -f .env ]; then
  if [ -f .env.example ]; then
    cp .env.example .env
    echo -e "${YELLOW}A new .env file was created from .env.example.${NC}"
    echo -e "${YELLOW}Please edit .env now (set DATABASE_URL, AUTH_SECRET, APP_URL) and run 'bash setup.sh' again.${NC}"
    exit 1
  else
    echo "ERROR: .env.example not found. Cannot continue."; exit 1
  fi
fi

# 2. Install dependencies
echo -e "${CYAN}Installing dependencies (this can take a few minutes)...${NC}"
if command -v npm >/dev/null 2>&1; then
  npm install
else
  echo "ERROR: npm not found. On cPanel, first 'Enter to the virtual environment' shown by the Node.js App, then run this again."
  exit 1
fi

# 3. Run the rest (db + build) via the node helper
npm run setup

echo -e "${GREEN}${BOLD}Setup finished. Now go to cPanel > Setup Node.js App and click RESTART.${NC}"
