#!/usr/bin/env bash
set -euo pipefail

echo "==> 0) Criar branch (opcional)"
# git checkout -b refactor/estrutura-src

echo "==> 1) Criar pastas da nova estrutura"
mkdir -p src/{config,db,repositories,services,domain/normalize,mqtt/handlers,middleware,routes}
mkdir -p src/db/migrations

echo "==> 2) Mover ficheiros principais"
# app/server
mv app.js src/app.js
mv server.js src/server.js

# db
mv db.js src/db/knex.js

# knexfile continua na raiz (ok)

echo "==> 3) Mover routes"
mv routes/chargers.js src/routes/chargers.routes.js
mv routes/charger_sessions.js src/routes/sessions.routes.js
mv routes/push.js src/routes/push.routes.js
mv routes/users.js src/routes/users.routes.js

echo "==> 4) Mover middleware"
mv middleware/verifyToken.js src/middleware/auth.js

echo "==> 5) Mover MQTT"
mv mqtt/client.js src/mqtt/index.js

echo "==> 6) Mover pushService (utils -> services)"
mv utils/pushService.js src/services/push.service.js

echo "==> 7) Mover migrations"
mv migrations/* src/db/migrations/

echo "==> 8) Limpar pastas antigas (se vazias)"
rmdir routes 2>/dev/null || true
rmdir middleware 2>/dev/null || true
rmdir mqtt 2>/dev/null || true
rmdir utils 2>/dev/null || true
rmdir migrations 2>/dev/null || true

echo "==> 9) Criar placeholders úteis (opcional)"
touch src/config/index.js
touch src/services/{chargers.service.js,configs.service.js,sessions.service.js}
touch src/repositories/{chargers.repo.js,sessions.repo.js,push.repo.js}
touch src/domain/normalize/{chargingStatus.js,chargingConfig.js}
touch src/middleware/{validate.js,errorHandler.js}
touch src/mqtt/publishers.js
touch src/mqtt/handlers/{evse.handler.js,meter.handler.js,legacy.handler.js}

echo "==> 10) Mostrar nova árvore (até 4 níveis)"
tree -a -L 4 src || true

echo "✅ Estrutura criada e ficheiros movidos."
echo "⚠️ Próximo passo: corrigir os imports/paths (vai quebrar até ajustar)."
