@echo off
chcp 65001 >nul
title Skeet Loader Server

echo ==========================================
echo   Skeet Loader - Server Deployment
echo ==========================================
echo.

:: Check Node.js
node --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Node.js is not installed!
    echo Download from: https://nodejs.org (LTS version)
    pause
    exit /b 1
)
echo Node.js: OK

:: Check npm
npm --version >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] npm not found!
    pause
    exit /b 1
)
echo npm: OK

:: Check if dependencies installed
if not exist "node_modules\" (
    echo Installing dependencies...
    npm install
    if %errorlevel% neq 0 (
        echo [ERROR] npm install failed!
        pause
        exit /b 1
    )
)
echo Dependencies: OK

:: Check RSA keys
if not exist "private.pem" (
    echo [ERROR] RSA keys not found! Generate them first:
    echo   openssl genrsa -out private.pem 2048
    echo   openssl rsa -in private.pem -pubout -out public.pem
    pause
    exit /b 1
)
echo RSA Keys: OK

:: Check if admin user exists
if not exist "skeet_server.db" (
    echo.
    echo No database found. Creating admin user...
    node setup.js
    if %errorlevel% neq 0 (
        echo [ERROR] Admin setup failed!
        pause
        exit /b 1
    )
)

:: Check PM2
echo.
where pm2 >nul 2>&1
if %errorlevel% equ 0 (
    echo PM2 found - starting with PM2...
    pm2 start ecosystem.config.js
    pm2 status
    echo.
    echo Server started with PM2! Commands:
    echo   pm2 status     - View status
    echo   pm2 logs       - View logs
    echo   pm2 restart skeet-server
    echo   pm2 stop skeet-server
) else (
    echo PM2 not installed - starting directly...
    echo To install PM2: npm install -g pm2
    echo.
    echo Starting server directly (Ctrl+C to stop)...
    node server.js
)

echo.
echo ==========================================
echo   Server should be running on port 3000
echo   Test: curl http://localhost:3000/api/status
echo ==========================================
pause
