# Enamel Wallet - Backend Migration Guide
## From Supabase to Node.js Backend

This guide will help you migrate your Enamel Wallet application from Supabase to a custom Node.js backend.

## Overview

The migration involves:
1. Setting up a PostgreSQL database
2. Running the Node.js backend server
3. Updating frontend environment variables
4. Testing the integration

## Prerequisites

- Node.js 18+ installed
- PostgreSQL 14+ installed
- Git (for version control)

## Step 1: Database Setup

### Install PostgreSQL

**macOS (using Homebrew)**:
```bash
brew install postgresql@14
brew services start postgresql@14
```

**Ubuntu/Debian**:
```bash
sudo apt update
sudo apt install postgresql postgresql-contrib
sudo systemctl start postgresql
sudo systemctl enable postgresql
```

**Windows**:
Download and install from [postgresql.org](https://www.postgresql.org/download/windows/)

### Create Database

```bash
# Access PostgreSQL
sudo -u postgres psql

# Create database and user
CREATE DATABASE enamel_wallet;
CREATE USER enamel_admin WITH ENCRYPTED PASSWORD 'your_secure_password';
GRANT ALL PRIVILEGES ON DATABASE enamel_wallet TO enamel_admin;

# Exit
\q
```

### Run Database Schema

```bash
cd backend
psql -U enamel_admin -d enamel_wallet -f src/database/schema.sql
```

Or if using default postgres user:
```bash
psql -d enamel_wallet -f src/database/schema.sql
```

## Step 2: Backend Setup

### Install Backend Dependencies

```bash
cd backend
npm install
```

### Configure Environment Variables

```bash
cp .env.example .env
```

Edit `backend/.env` with your values:

```env
# Server Configuration
NODE_ENV=development
PORT=5000
API_URL=http://localhost:5000

# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=enamel_wallet
DB_USER=enamel_admin
DB_PASSWORD=your_secure_password

# JWT Configuration
JWT_SECRET=your_super_secret_jwt_key_minimum_32_characters_long
JWT_REFRESH_SECRET=your_super_secret_refresh_token_key_also_32_chars
JWT_EXPIRES_IN=24h
JWT_REFRESH_EXPIRES_IN=7d

# Paystack Configuration
PAYSTACK_SECRET_KEY=sk_test_your_paystack_secret_key
PAYSTACK_PUBLIC_KEY=pk_test_your_paystack_public_key

# Prembly KYC Configuration
PREMBLY_API_KEY=your_prembly_api_key
PREMBLY_APP_ID=your_prembly_app_id

# CORS Configuration
CORS_ORIGIN=http://localhost:5173

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
```

### Start Backend Server

**Development Mode**:
```bash
npm run dev
```

The server will start on http://localhost:5000

**Production Mode**:
```bash
npm run build
npm start
```

### Verify Backend is Running

Test the health endpoint:
```bash
curl http://localhost:5000/health
```

Expected response:
```json
{
  "status": "ok",
  "timestamp": "2025-10-19T..."
}
```

## Step 3: Frontend Setup

### Update Frontend Environment Variables

Create or update `.env` in your frontend root:

```env
VITE_API_URL=http://localhost:5000/api
```

For production, use your deployed backend URL:
```env
VITE_API_URL=https://your-backend-url.com/api
```

### Install Frontend Dependencies (if needed)

```bash
npm install
```

### Remove Supabase Dependencies (Optional)

You can now remove Supabase-related files:

```bash
# Remove Supabase utilities
rm -rf utils/supabase

# Remove Supabase functions
rm -rf supabase/functions
```

Update `package.json` to remove Supabase dependencies if you're not using them elsewhere:
```json
// Remove these if present
"@supabase/supabase-js": "^2.x.x"
```

## Step 4: Testing

### Test Authentication

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

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

Save the returned token for authenticated requests.

### Test Authenticated Endpoints

```bash
# Get user profile
curl http://localhost:5000/api/users/profile \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

# Get wallets
curl http://localhost:5000/api/wallets \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"
```

### Test Frontend Integration

1. Start the frontend:
```bash
npm run dev
```

2. Open http://localhost:5173
3. Try signing up a new user
4. Login with the credentials
5. Test wallet features, transactions, etc.

## Step 5: Create Admin User

### Manual Method (Direct Database)

```bash
# Connect to database
psql -U enamel_admin -d enamel_wallet

# Update a user's role to admin
UPDATE users SET role = 'admin' WHERE email = 'your-admin@email.com';

# Exit
\q
```

### Programmatic Method

Create a script `backend/create-admin.js`:

```javascript
const bcrypt = require('bcrypt');
const { Pool } = require('pg');
require('dotenv').config();

const pool = new Pool({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
});

async function createAdmin() {
  const email = 'admin@enamelwallet.com';
  const password = 'AdminPassword123!'; // Change this!
  const hashedPassword = await bcrypt.hash(password, 10);
  
  const accountNumber = '30' + Math.floor(Math.random() * 100000000).toString().padStart(8, '0');
  
  await pool.query(
    `INSERT INTO users (id, email, password, first_name, last_name, account_number, role, created_at)
     VALUES (uuid_generate_v4(), $1, $2, 'Admin', 'User', $3, 'admin', NOW())
     ON CONFLICT (email) DO UPDATE SET role = 'admin'`,
    [email, hashedPassword, accountNumber]
  );
  
  console.log('Admin user created!');
  console.log('Email:', email);
  console.log('Password:', password);
  
  pool.end();
}

createAdmin();
```

Run it:
```bash
node create-admin.js
```

## Step 6: Data Migration (If Migrating from Existing Supabase)

If you have existing data in Supabase:

### Export from Supabase

```bash
# Using Supabase CLI
supabase db dump -f supabase_dump.sql
```

### Transform and Import

The schema might differ slightly. You may need to:
1. Adjust column names (snake_case vs camelCase)
2. Update UUID generation
3. Transform data types

Create a migration script or manually adjust the dump file, then:

```bash
psql -U enamel_admin -d enamel_wallet -f transformed_dump.sql
```

## Step 7: Deployment

### Backend Deployment Options

#### Option 1: Railway
1. Create account at [railway.app](https://railway.app)
2. New Project → Deploy from GitHub
3. Add PostgreSQL database
4. Set environment variables
5. Deploy

#### Option 2: Heroku
```bash
heroku create enamel-wallet-api
heroku addons:create heroku-postgresql:hobby-dev
heroku config:set JWT_SECRET=your_secret
# Set other env vars
git push heroku main
```

#### Option 3: DigitalOcean App Platform
1. Create new app from GitHub
2. Add PostgreSQL database
3. Configure environment variables
4. Deploy

#### Option 4: VPS (Ubuntu)
```bash
# SSH to your server
ssh user@your-server-ip

# Install Node.js and PostgreSQL
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs postgresql

# Clone and setup
git clone your-repo
cd enamel-wallet/backend
npm install
npm run build

# Setup PM2
npm install -g pm2
pm2 start dist/server.js --name enamel-api
pm2 startup
pm2 save

# Setup Nginx reverse proxy
sudo apt install nginx
# Configure nginx to proxy to localhost:5000
```

### Frontend Deployment

Update your frontend `.env` with production backend URL:
```env
VITE_API_URL=https://your-backend.railway.app/api
```

Then deploy frontend to Vercel/Netlify as before.

## Troubleshooting

### Database Connection Issues

```bash
# Check PostgreSQL is running
sudo systemctl status postgresql

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

# Check logs
tail -f backend/logs/error.log
```

### CORS Issues

Ensure `CORS_ORIGIN` in backend `.env` matches your frontend URL:
```env
# Development
CORS_ORIGIN=http://localhost:5173

# Production
CORS_ORIGIN=https://your-app.vercel.app
```

### JWT Issues

Ensure JWT secrets are set and are long enough (minimum 32 characters):
```bash
# Generate secure secrets
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```

### Port Already in Use

```bash
# Find process using port 5000
lsof -i :5000

# Kill it
kill -9 <PID>

# Or use different port in .env
PORT=5001
```

## Post-Migration Checklist

- [ ] Database created and schema applied
- [ ] Backend server running without errors
- [ ] Environment variables configured
- [ ] Frontend can connect to backend
- [ ] Sign up works
- [ ] Login works
- [ ] Wallet operations work
- [ ] Transactions work
- [ ] Admin dashboard accessible
- [ ] Admin user created
- [ ] Production deployment planned
- [ ] Backups configured
- [ ] Monitoring setup

## Performance Tips

1. **Database Indexing**: Already included in schema
2. **Connection Pooling**: Configured in connection.ts
3. **Caching**: Consider Redis for sessions
4. **Rate Limiting**: Already configured
5. **Logging**: Winston configured, monitor logs

## Security Checklist

- [ ] Strong JWT secrets in production
- [ ] Database credentials secured
- [ ] HTTPS enabled in production
- [ ] CORS properly configured
- [ ] Rate limiting enabled
- [ ] Input validation on all endpoints
- [ ] SQL injection prevention (using parameterized queries)
- [ ] Password hashing with bcrypt
- [ ] Environment variables not committed to Git

## Support

If you encounter issues:
1. Check backend logs: `backend/logs/error.log`
2. Check database connection
3. Verify environment variables
4. Test endpoints with curl/Postman
5. Check frontend console for errors

## Rollback Plan

If you need to rollback to Supabase:
1. Keep Supabase project active during migration
2. Don't delete Supabase files until migration is complete
3. Keep database backups
4. Test thoroughly before full cutover

## Next Steps

After successful migration:
1. Set up automated database backups
2. Configure monitoring (e.g., Sentry, LogRocket)
3. Set up CI/CD pipeline
4. Performance testing
5. Security audit
6. Load testing

---

**Migration Complete! 🎉**

Your Enamel Wallet app is now running on a custom Node.js backend with full control over your infrastructure.
