# Enamel Wallet - Node.js Backend Implementation

## Overview

Your Enamel Wallet application has been successfully migrated from Supabase to a custom Node.js backend. This gives you complete control over your infrastructure, data, and business logic.

## What Changed?

### Backend (New!)

**New Directory Structure**:
```
backend/
├── src/
│   ├── server.ts              # Express server setup
│   ├── database/
│   │   ├── connection.ts      # PostgreSQL connection
│   │   └── schema.sql         # Database schema
│   ├── middleware/
│   │   ├── auth.ts           # JWT authentication
│   │   ├── errorHandler.ts   # Error handling
│   │   ├── requestLogger.ts  # Request logging
│   │   └── validation.ts     # Input validation
│   ├── routes/
│   │   ├── auth.ts           # Authentication routes
│   │   ├── users.ts          # User management
│   │   ├── wallets.ts        # Wallet operations
│   │   ├── transactions.ts   # Transaction history
│   │   ├── payments.ts       # Payment processing
│   │   ├── groupSavings.ts   # Group savings
│   │   ├── kyc.ts            # KYC verification
│   │   ├── admin.ts          # Admin operations
│   │   └── system.ts         # System health
│   └── utils/
│       └── logger.ts         # Winston logger
├── package.json
├── tsconfig.json
├── .env.example
└── README.md
```

### Frontend Updates

**New Files**:
- `/utils/api.ts` - API client for Node.js backend
- `/.env.example` - Frontend environment configuration

**Modified Files**:
- `/utils/auth.ts` - Updated to use new API client

**Removed Dependencies** (can be removed):
- Supabase client files in `/utils/supabase/`
- Supabase functions in `/supabase/functions/`

## Architecture

### Previous (Supabase)
```
Frontend → Supabase Client → Supabase Cloud
                              ↓
                         PostgreSQL (Managed)
```

### Current (Node.js)
```
Frontend → API Client → Node.js Backend → PostgreSQL
                        ↓
                     JWT Auth, Business Logic
```

## Key Features

### 🔐 Authentication & Security
- JWT-based authentication
- Bcrypt password hashing
- Transaction PIN verification
- Role-based access control (User, Staff, Admin)
- Rate limiting
- Helmet.js security headers

### 💰 Financial Operations
- Dual wallet system (Spend & Savings)
- P2P transfers with PIN verification
- Utility payments (airtime, data, bills)
- Transaction history with filtering
- Account crediting (admin/staff)

### 👥 Group Savings
- Create savings groups
- Join existing groups
- Position-based payout system
- Member management

### ✅ KYC & Compliance
- BVN verification (Prembly integration ready)
- Document submission
- Status tracking
- Admin approval workflow

### 👨‍💼 Admin Dashboard
- User management
- Transaction monitoring
- System statistics
- Activity logs
- Account crediting
- User deletion

### 📊 System Monitoring
- Health checks
- Performance metrics
- Database monitoring
- CPU and memory usage
- Transaction analytics

## API Endpoints

### Authentication
```
POST   /api/auth/signup        Register new user
POST   /api/auth/login         Login user
```

### User Management
```
GET    /api/users/profile      Get user profile
PUT    /api/users/profile      Update profile
POST   /api/users/set-pin      Set transaction PIN
GET    /api/users/find/:id     Find user by account
```

### Wallets
```
GET    /api/wallets            Get all user wallets
GET    /api/wallets/:type/balance   Get wallet balance
```

### Transactions
```
GET    /api/transactions       Get transaction history
GET    /api/transactions/:id   Get transaction details
```

### Payments
```
POST   /api/payments/transfer  P2P transfer
POST   /api/payments/utility   Utility payment
```

### Group Savings
```
POST   /api/group-savings           Create group
GET    /api/group-savings           Get user groups
POST   /api/group-savings/:id/join  Join group
GET    /api/group-savings/:id/members   Get members
```

### KYC
```
POST   /api/kyc/submit         Submit KYC
GET    /api/kyc/status         Get KYC status
POST   /api/kyc/verify-bvn     Verify BVN
```

### Admin (Protected)
```
GET    /api/admin/users        Get all users
DELETE /api/admin/users/:id    Delete user
POST   /api/admin/credit       Credit account
GET    /api/admin/stats        Dashboard stats
GET    /api/admin/activities   Recent activities
```

### System (Admin Only)
```
GET    /api/system/health      System health
GET    /api/system/metrics     System metrics
```

## Database Schema

### Tables
- **users** - User accounts, authentication, KYC status
- **wallets** - User wallets (spend/savings)
- **transactions** - All financial transactions
- **savings_groups** - Group savings information
- **group_members** - Group membership
- **kyc_documents** - KYC verification documents
- **notifications** - User notifications

### Indexes
Optimized indexes for:
- User lookups (email, phone, account number)
- Transaction queries (sender, recipient, date)
- Wallet operations
- Group memberships

## Getting Started

### Quick Start (All-in-One)

```bash
# Make the script executable
chmod +x backend/quick-start.sh

# Run it
./backend/quick-start.sh
```

### Manual Setup

1. **Install Backend Dependencies**:
```bash
cd backend
npm install
```

2. **Setup Environment**:
```bash
cp .env.example .env
# Edit .env with your configuration
```

3. **Create Database**:
```bash
createdb enamel_wallet
psql -d enamel_wallet -f src/database/schema.sql
```

4. **Start Backend**:
```bash
npm run dev
```

5. **Setup Frontend**:
```bash
# In root directory
cp .env.example .env
# Edit .env: VITE_API_URL=http://localhost:5000/api
```

6. **Start Frontend**:
```bash
npm run dev
```

### Using Convenience Scripts

Start both frontend and backend:
```bash
npm run dev:all
```

Start backend only:
```bash
npm run dev:backend
```

## Environment Variables

### Backend (`/backend/.env`)
```env
NODE_ENV=development
PORT=5000
DB_HOST=localhost
DB_PORT=5432
DB_NAME=enamel_wallet
DB_USER=postgres
DB_PASSWORD=your_password
JWT_SECRET=your_jwt_secret
JWT_REFRESH_SECRET=your_refresh_secret
PAYSTACK_SECRET_KEY=your_paystack_key
PREMBLY_API_KEY=your_prembly_key
CORS_ORIGIN=http://localhost:5173
```

### Frontend (`/.env`)
```env
VITE_API_URL=http://localhost:5000/api
```

## Development Workflow

### Starting Development

```bash
# Terminal 1: Backend
cd backend
npm run dev

# Terminal 2: Frontend
npm run dev
```

Or use concurrently:
```bash
npm run dev:all
```

### Making API Changes

1. Update route in `/backend/src/routes/`
2. Update API client in `/utils/api.ts`
3. Update component to use new endpoint
4. Test thoroughly

### Database Changes

1. Update schema in `/backend/src/database/schema.sql`
2. Create migration script if needed
3. Apply to database:
```bash
psql -d enamel_wallet -f src/database/schema.sql
```

## Deployment

### Backend Deployment

**Option 1: Railway** (Recommended)
```bash
# Install Railway CLI
npm install -g @railway/cli

# Login and deploy
railway login
railway init
railway up
```

**Option 2: Heroku**
```bash
heroku create enamel-wallet-api
heroku addons:create heroku-postgresql:hobby-dev
git push heroku main
```

**Option 3: DigitalOcean**
- Use App Platform
- Connect GitHub repository
- Add PostgreSQL database
- Configure environment variables

**Option 4: VPS**
```bash
# Setup on Ubuntu server
# Install Node.js, PostgreSQL, Nginx
# Use PM2 for process management
pm2 start dist/server.js --name enamel-api
```

### Frontend Deployment

Update environment variable:
```env
VITE_API_URL=https://your-backend-url.com/api
```

Deploy to Vercel:
```bash
vercel --prod
```

## Testing

### Test Backend

```bash
# Health check
curl http://localhost:5000/health

# Sign up
curl -X POST http://localhost:5000/api/auth/signup \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "Test1234!",
    "firstName": "Test",
    "lastName": "User"
  }'

# Login
curl -X POST http://localhost:5000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "identifier": "test@example.com",
    "password": "Test1234!"
  }'
```

### Test Frontend Integration

1. Sign up new user
2. Login
3. Check wallet balances
4. Try P2P transfer (set PIN first)
5. View transaction history
6. Test group savings
7. Test admin features (as admin user)

## Admin User Creation

### Method 1: Direct Database
```sql
-- Connect to database
psql -d enamel_wallet

-- Update user role
UPDATE users SET role = 'admin' 
WHERE email = 'your-email@example.com';
```

### Method 2: Using Script
See `BACKEND_MIGRATION_GUIDE.md` for detailed script.

## Monitoring & Logs

### Application Logs
```bash
# View logs
tail -f backend/logs/combined.log
tail -f backend/logs/error.log
```

### Database Logs
```bash
# PostgreSQL logs location varies by OS
# macOS (Homebrew): /usr/local/var/log/postgresql@14/
# Ubuntu: /var/log/postgresql/
```

### System Health
```bash
# Check system health (requires admin token)
curl http://localhost:5000/api/system/health \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
```

## Troubleshooting

### Common Issues

**1. Database Connection Error**
```bash
# Check PostgreSQL is running
sudo systemctl status postgresql

# Check connection
psql -U postgres -d enamel_wallet -c "SELECT 1;"
```

**2. Port Already in Use**
```bash
# Find and kill process
lsof -i :5000
kill -9 <PID>
```

**3. CORS Errors**
- Check `CORS_ORIGIN` in backend `.env`
- Ensure it matches frontend URL

**4. JWT Authentication Fails**
- Check JWT_SECRET is set
- Ensure token is included in requests
- Verify token hasn't expired

**5. Frontend Can't Connect**
- Check `VITE_API_URL` in frontend `.env`
- Ensure backend is running
- Check browser console for errors

## Performance Tips

1. **Database Connection Pooling**: Already configured (max 20 connections)
2. **Indexing**: Indexes created automatically
3. **Caching**: Consider adding Redis for sessions
4. **Rate Limiting**: Configured (100 requests per 15 minutes)
5. **Logging**: Use Winston levels appropriately

## Security Best Practices

✅ **Implemented**:
- Password hashing (bcrypt)
- JWT authentication
- SQL injection prevention (parameterized queries)
- CORS protection
- Helmet.js security headers
- Rate limiting
- Input validation
- Role-based access control

⚠️ **Recommended for Production**:
- Enable HTTPS
- Use secure JWT secrets (32+ characters)
- Regular security audits
- Keep dependencies updated
- Implement 2FA
- Add request logging and monitoring
- Database backups
- DDoS protection

## Migration Benefits

### Before (Supabase)
- ❌ Limited to Supabase features
- ❌ Vendor lock-in
- ❌ Pricing based on usage
- ❌ Limited customization

### After (Node.js)
- ✅ Full control over infrastructure
- ✅ No vendor lock-in
- ✅ Predictable costs
- ✅ Custom business logic
- ✅ Easier debugging
- ✅ Better performance tuning
- ✅ Learn backend development

## Next Steps

1. **Test thoroughly** - Ensure all features work
2. **Create admin user** - For dashboard access
3. **Configure integrations** - Paystack, Prembly
4. **Set up monitoring** - Logs, alerts
5. **Plan deployment** - Choose hosting provider
6. **Database backups** - Automate backups
7. **Documentation** - Document custom changes
8. **Performance testing** - Load testing
9. **Security audit** - Review security
10. **Go live!** 🚀

## Support & Resources

- **Backend README**: `/backend/README.md`
- **Migration Guide**: `/BACKEND_MIGRATION_GUIDE.md`
- **Database Schema**: `/backend/src/database/schema.sql`
- **API Client**: `/utils/api.ts`

## Contributing

When making changes:
1. Update API routes in `/backend/src/routes/`
2. Update API client in `/utils/api.ts`
3. Update types if needed in `/types/app.ts`
4. Test thoroughly
5. Update documentation

## License

MIT License - See LICENSE file for details

---

**Congratulations!** 🎉

You now have a fully functional Node.js backend for Enamel Wallet with complete control over your infrastructure!
