#!/usr/bin/env bash
#===============================================================================
# deploy.sh - Deploy Next.js + Payload CMS ไปยัง Easypanel
#
# Usage: ./deploy.sh [project-path] [server] [domain]
#
# Requirements:
# - git
# - npm
# - easypanel CLI (หรือใช้ web interface)
#
#===============================================================================

set -e

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

# Default values
PROJECT_PATH="${1:-.}"
SERVER="${2:-}"
DOMAIN="${3:-}"

#-------------------------------------------------------------------------------
# Helper functions
#-------------------------------------------------------------------------------

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_usage() {
    cat << EOF
Usage: $(basename "$0") [project-path] [server] [domain]

Deploy Next.js + Payload CMS ไปยัง Easypanel

Arguments:
  project-path    ที่อยู่ project (default: current directory)
  server         ชื่อ easypanel server
  domain         domain ที่จะใช้ (เช่น example.com)

Examples:
  $(basename "$0") /path/to/project my-server example.com
  $(basename "$0") . openclaw-vps techvision.co.th

EOF
}

#-------------------------------------------------------------------------------
# Pre-flight checks
#-------------------------------------------------------------------------------

check_requirements() {
    log_info "ตรวจสอบความต้องการ..."

    if ! command -v git &> /dev/null; then
        log_error "git ไม่พบ"
        exit 1
    fi

    if ! command -v npm &> /dev/null; then
        log_error "npm ไม่พบ"
        exit 1
    fi

    cd "$PROJECT_PATH"

    if [ ! -f "package.json" ]; then
        log_error "ไม่พบ package.json"
        exit 1
    fi

    if [ ! -f "next.config.ts" ] && [ ! -f "next.config.js" ]; then
        log_error "ไม่พบ next.config.ts หรือ next.config.js"
        exit 1
    fi

    log_success "ความต้องการพื้นฐานผ่าน"
}

#-------------------------------------------------------------------------------
# Check git status
#-------------------------------------------------------------------------------

check_git() {
    log_info "ตรวจสอบ git..."

    if [ ! -d ".git" ]; then
        log_warning "ไม่พบ .git directory"
        log_info "กำลังสร้าง git repo..."
        git init
        git add .
        git commit -m "Initial commit"
        log_success "สร้าง git repo เสร็จสมบูรณ์"
    else
        log_success "พบ git repo"
    fi
}

#-------------------------------------------------------------------------------
# Build project
#-------------------------------------------------------------------------------

build_project() {
    log_info "Build project..."

    cd "$PROJECT_PATH"

    # Install dependencies
    log_info "ติดตั้ง dependencies..."
    npm install

    # Build
    log_info "กำลัง build..."
    npm run build

    if [ $? -eq 0 ]; then
        log_success "Build เสร็จสมบูรณ์"
    else
        log_error "Build ล้มเหลว"
        exit 1
    fi
}

#-------------------------------------------------------------------------------
# Check build output
#-------------------------------------------------------------------------------

check_build_output() {
    log_info "ตรวจสอบ build output..."

    cd "$PROJECT_PATH"

    if [ -d "dist" ]; then
        local file_count=$(find dist -type f | wc -l)
        local size=$(du -sh dist | cut -f1)
        log_success "พบ dist/ ($file_count files, $size)"
    else
        log_error "ไม่พบ dist/ directory"
        exit 1
    fi
}

#-------------------------------------------------------------------------------
# Deploy instructions
#-------------------------------------------------------------------------------

show_deploy_instructions() {
    echo ""
    echo "=============================================="
    echo "  Deploy Instructions"
    echo "=============================================="
    echo ""
    echo "  Project: $PROJECT_PATH"
    echo "  Server: $SERVER"
    echo "  Domain: $DOMAIN"
    echo ""
    echo "  ขั้นตอนการ deploy บน Easypanel:"
    echo ""
    echo "  1. เปิด Easypanel dashboard"
    echo "  2. สร้าง project ใหม่"
    echo "  3. เลือก 'Deploy from Git'"
    echo "  4. ใส่ git repo URL"
    echo "  5. ตั้งค่า environment variables:"
    echo "     - PAYLOAD_SECRET"
    echo "     - MONGODB_URL"
    echo "  6. ตั้งค่า domain: $DOMAIN"
    echo "  7. Deploy"
    echo ""
    echo "  หรือใช้ easypanel CLI:"
    echo ""
    echo "    ep project create --name $PROJECT_NAME --server $SERVER"
    echo "    ep project deploy \$PROJECT_ID --git"
    echo ""
}

#-------------------------------------------------------------------------------
# Create deploy config
#-------------------------------------------------------------------------------

create_deploy_config() {
    log_info "สร้าง deploy config..."

    cd "$PROJECT_PATH"

    mkdir -p .easypanel

    cat > .easypanel/deploy.json << EOF
{
  "name": "$PROJECT_NAME",
  "server": "$SERVER",
  "domain": "$DOMAIN",
  "build": {
    "command": "npm run build",
    "output": ".next"
  },
  "environment": {
    "NODE_ENV": "production"
  },
  "required_env": [
    "PAYLOAD_SECRET",
    "MONGODB_URL"
  ]
}
EOF

    log_success "สร้าง .easypanel/deploy.json เสร็จสมบูรณ์"
}

#-------------------------------------------------------------------------------
# Main
#-------------------------------------------------------------------------------

main() {
    echo "=============================================="
    echo "  Deploy Tool"
    echo "  Next.js + Payload CMS -> Easypanel"
    echo "=============================================="
    echo ""

    if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
        print_usage
        exit 0
    fi

    if [ -z "$SERVER" ]; then
        log_info "ไม่ได้ระบุ server - จะแสดงวิธี deploy"
        SERVER="<your-server>"
    fi

    if [ -z "$DOMAIN" ]; then
        DOMAIN="<your-domain.com>"
    fi

    PROJECT_NAME=$(basename "$PROJECT_PATH")

    check_requirements
    check_git
    build_project
    check_build_output
    create_deploy_config
    show_deploy_instructions

    echo ""
    echo "=============================================="
    log_success "พร้อม deploy!"
    echo "=============================================="
}

main "$@"
