#!/bin/bash

echo "==================================="
echo "   SAMATORTRACK PRODUCTION BUILD"
echo "==================================="
echo

echo "[1/6] Checking Node.js installation..."
if ! command -v node &> /dev/null; then
    echo "ERROR: Node.js not found! Please install Node.js first."
    exit 1
fi
echo "Node.js: $(node --version) - OK"

echo
echo "[2/6] Navigating to frontend directory..."
if [ ! -d "frontend" ]; then
    echo "ERROR: Frontend directory not found!"
    exit 1
fi
cd frontend
echo "Directory: OK"

echo
echo "[3/6] Installing dependencies..."
if ! npm install; then
    echo "ERROR: Failed to install dependencies!"
    exit 1
fi
echo "Dependencies: OK"

echo
echo "[4/6] Building for production..."
if ! npm run build; then
    echo "ERROR: Build failed!"
    exit 1
fi
echo "Build: OK"

echo
echo "[5/6] Verifying build output..."
if [ ! -f "dist/index.html" ]; then
    echo "ERROR: Build output not found!"
    exit 1
fi
echo "Build output: OK"

echo
echo "[6/6] Copying to public directory..."
if [ -f "../public/index.html" ]; then
    echo "Backing up existing files..."
    mkdir -p "../public/backup"
    cp -r ../public/* ../public/backup/ 2>/dev/null || true
fi

echo "Copying new files..."
if ! cp -r dist/* ../public/; then
    echo "ERROR: Failed to copy files!"
    exit 1
fi
echo "Copy: OK"

echo
echo "==================================="
echo "      BUILD COMPLETED SUCCESSFULLY!"
echo "==================================="
echo
echo "Build output location: frontend/dist/"
echo "Deployed to: public/"
echo
echo "Next steps:"
echo "1. Test the application at http://localhost:8000"
echo "2. Verify all features are working"
echo "3. Deploy to production server"
echo

read -p "Press Enter to continue..."