#!/usr/bin/env bash
# Run from /var/www/html/ranchlands: bash apply-patch.sh
set -e
DIR="$(cd "$(dirname "$0")" && pwd)"
FLAT="$DIR/server/dist"

echo "=== Ranchlands Patch: Seasons, Hay & Free Breeding ==="

for DEST in "$FLAT/routes" "$FLAT/server/src/routes"; do
    [ -d "$DEST" ] || continue
    echo "  → $DEST"
    cp "$FLAT/routes/breed.js"    "$DEST/breed.js"
    cp "$FLAT/routes/herd.js"     "$DEST/herd.js"
    cp "$FLAT/routes/ranch.js"    "$DEST/ranch.js"
    cp "$FLAT/routes/calendar.js" "$DEST/calendar.js"
done

for DEST in "$FLAT/db" "$FLAT/server/src/db"; do
    [ -d "$DEST" ] || continue
    echo "  → $DEST"
    cp "$FLAT/db/migrate.js" "$DEST/migrate.js"
done

for DEST in "$FLAT" "$FLAT/server/src"; do
    [ -f "$DEST/index.js" ] || continue
    echo "  → $DEST/index.js"
    cp "$FLAT/index.js" "$DEST/index.js"
done

echo ""
echo "Running new migrations (game clock, inventory, animal housing)..."
cd "$DIR"
npm run db:migrate

echo ""
echo "Restarting PM2..."
pm2 restart ranchlands

echo ""
echo "=== Done! ==="
echo ""
echo "New API endpoints:"
echo "  GET  /api/v1/calendar              - current season, game day, year"
echo "  GET  /api/v1/calendar/inventory    - your hay bale count"
echo "  POST /api/v1/calendar/store/buy    - buy hay {itemType:'hay_bale', quantity:20}"
echo "  POST /api/v1/herd/:id/housing      - move animal {housing:'pasture'|'corral'|'barn'}"
echo ""
echo "Season rules:"
echo "  Spring/Summer/Fall: feeding is FREE (pasture grazing)"
echo "  Winter: feeding costs 1 hay bale per animal"
echo "  Pastures: locked in winter — use corrals instead"
echo "  New buildings: pasture_small, pasture_large, corral"
echo ""
pm2 logs ranchlands --lines 15 --nostream
