#!/bin/bash

# ==============================================================================
# Bigbike Project (bigbike.ddcsprocket.com)
# Deployment Script (post-receive hook) on sql@192.168.1.26
# Role: Application Runner (PM2 / Bun / Node) - No local Nginx
# ==============================================================================

set -e
export PATH="/home/sql/.bun/bin:/usr/local/bin:/usr/bin:/bin:$PATH"

# 1. PATH CONFIG
GIT_DIR="/home/sql/git/bigbike.git"
WORK_DIR="/home/sql/code/bigbike"
TARGET_ADMIN="/var/www/html/bigbike_admin"
BRANCH="master"
TEMP_DIR="/tmp/bigbike_build_$(date +%s)"

# 2. RUNTIMES & EXECUTABLES
BUN="/home/sql/.bun/bin/bun"
NODE="/usr/bin/node"
PM2="/usr/bin/pm2"

# 3. PM2 PROCESS NAMES
PM2_NAME_BACKEND="bigbike-backend"
PM2_NAME_WEBSITE="bigbike-website"

# 4. ASSIGNED PORTS (Direct forwarded from outer proxy / gateway)
# (Port 3001 is shop-ddcth, 4000 is aroka, 5000 is ddc hr)
BACKEND_PORT=3005
SSR_PORT=3002

# 5. ENVIRONMENT VARIABLES
export PORT="$SSR_PORT"
export BACKEND_PORT="$BACKEND_PORT"
export VITE_API_URL="https://api.bigbike.ddcsprocket.com/api"
export NEXT_PUBLIC_API_URL="https://api.bigbike.ddcsprocket.com/api"

echo "========================================================"
echo "🚀 [Bigbike] Starting Deployment on 192.168.1.26..."
echo "========================================================"

# A. Checkout code to Work Directory
mkdir -p "$WORK_DIR"
echo ">>> Checking out branch $BRANCH to $WORK_DIR..."
git --work-tree="$WORK_DIR" --git-dir="$GIT_DIR" checkout -f "$BRANCH"

cd "$WORK_DIR"

# B. Install dependencies
if [ -f "package.json" ]; then
  echo ">>> Installing dependencies with Bun..."
  $BUN install
fi

# C. Setup Backend (if apps/backend exists)
if [ -d "apps/backend" ]; then
  echo ">>> Setting up Backend..."
  cd "$WORK_DIR/apps/backend"
  
  if [ -f "prisma/schema.prisma" ]; then
    echo ">>> Generating Prisma Client..."
    $BUN x prisma generate

    echo ">>> Auto-updating Database Schema..."
    if [ -d "prisma/migrations" ]; then
      echo ">>> Running Prisma migrate deploy..."
      $BUN x prisma migrate deploy || echo "⚠️ migrate deploy had notices, falling back to db push..."
    fi
    echo ">>> Syncing schema with db push..."
    $BUN x prisma db push --accept-data-loss
  fi

  echo ">>> Restarting PM2 process: $PM2_NAME_BACKEND..."
  if $PM2 describe "$PM2_NAME_BACKEND" > /dev/null 2>&1; then
    $PM2 restart "$PM2_NAME_BACKEND" --update-env
  else
    echo ">>> Starting $PM2_NAME_BACKEND for the first time on port $BACKEND_PORT..."
    PORT=$BACKEND_PORT $PM2 start "$BUN" --name "$PM2_NAME_BACKEND" --cwd "$WORK_DIR/apps/backend" -- run src/index.ts
  fi
  cd "$WORK_DIR"
fi

# D. Build & Deploy Admin Panel (React Vite SPA)
if [ -d "apps/admin" ]; then
  echo ">>> Building Admin Panel (React Vite SPA)..."
  cd "$WORK_DIR/apps/admin"
  export VITE_API_URL="https://api.bigbike.ddcsprocket.com/api"
  export VITE_FRONTEND_URL="https://bigbike.ddcsprocket.com"
  $BUN run build

  if [ -d "$TARGET_ADMIN" ]; then
    echo "Deploying Admin Panel to $TARGET_ADMIN..."
    rsync -av --delete dist/ "$TARGET_ADMIN"/
  else
    echo "⚠️ Target directory $TARGET_ADMIN not found. Please create it once with:"
    echo "   sudo mkdir -p $TARGET_ADMIN && sudo chown -R sql:sql $TARGET_ADMIN"
  fi
  cd "$WORK_DIR"
fi

# E. Setup Website SSR (if apps/website exists)
if [ -d "apps/website" ]; then
  echo ">>> Building Next.js Website..."
  cd "$WORK_DIR/apps/website"
  NODE_ENV=production $BUN run build

  echo ">>> Restarting PM2 process: $PM2_NAME_WEBSITE..."
  if $PM2 describe "$PM2_NAME_WEBSITE" > /dev/null 2>&1; then
    PORT=$SSR_PORT $PM2 restart "$PM2_NAME_WEBSITE" --update-env
  else
    echo ">>> Starting $PM2_NAME_WEBSITE for the first time on port $SSR_PORT..."
    # Check standalone server or standard next start
    if [ -f ".next/standalone/server.js" ]; then
      PORT=$SSR_PORT $PM2 start "$NODE" --name "$PM2_NAME_WEBSITE" --cwd "$WORK_DIR/apps/website/.next/standalone" -- server.js
    else
      PORT=$SSR_PORT $PM2 start "$BUN" --name "$PM2_NAME_WEBSITE" --cwd "$WORK_DIR/apps/website" -- run start
    fi
  fi
  cd "$WORK_DIR"
fi

# F. Save PM2 state
$PM2 save

echo "========================================================"
echo "✅ [Bigbike] Deployment Finished Successfully!"
echo "========================================================"
$PM2 status
