# PWA Deployment Guide

This guide covers deploying the Echoes of the Ashes PWA to production.

## Prerequisites

1. Docker and Docker Compose installed
2. Traefik reverse proxy running
3. DNS record for `echoesoftheashgame.patacuack.net` pointing to your server
4. `.env` file configured with database credentials

## Initial Setup

### 1. Run Database Migration

Before starting the API service, run the migration to add web authentication support:

```bash
docker exec -it echoes_of_the_ashes_bot python migrate_web_auth.py
```

This adds `username` and `password_hash` columns to the players table.

### 2. Set JWT Secret

Add to your `.env` file:

```bash
JWT_SECRET_KEY=your-super-secret-key-change-this-in-production
```

Generate a secure key:

```bash
openssl rand -hex 32
```

## Deployment Steps

### 1. Build and Start Services

```bash
docker-compose up -d --build echoes_of_the_ashes_api echoes_of_the_ashes_pwa
```

This will:
- Build the API backend (FastAPI)
- Build the PWA frontend (React + Nginx)
- Start both containers
- Connect to Traefik network
- Obtain SSL certificate via Let's Encrypt

### 2. Verify Services

Check logs:

```bash
# API logs
docker logs echoes_of_the_ashes_api

# PWA logs
docker logs echoes_of_the_ashes_pwa
```

Check health:

```bash
# API health
curl https://echoesoftheashgame.patacuack.net/api/

# PWA (should return HTML)
curl https://echoesoftheashgame.patacuack.net/
```

### 3. Test Authentication

Register a new account:

```bash
curl -X POST https://echoesoftheashgame.patacuack.net/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"username": "testuser", "password": "testpass123"}'
```

Should return:

```json
{
  "access_token": "eyJ...",
  "token_type": "bearer"
}
```

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      Traefik (Reverse Proxy)                │
│                                                              │
│  ┌──────────────────────────────────────────────────────┐  │
│  │  echoesoftheashgame.patacuack.net                    │  │
│  │  - HTTPS (Let's Encrypt)                             │  │
│  │  - Routes to PWA container                           │  │
│  └──────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
        ┌─────────────────────────────────────┐
        │  echoes_of_the_ashes_pwa (Nginx)   │
        │  - Serves React build               │
        │  - Proxies /api/* to API container  │
        │  - Service worker caching           │
        └─────────────────────────────────────┘
                            │
                            ▼ (API requests)
        ┌─────────────────────────────────────┐
        │  echoes_of_the_ashes_api (FastAPI) │
        │  - JWT authentication               │
        │  - Game state management            │
        │  - Database queries                 │
        └─────────────────────────────────────┘
                            │
                            ▼
        ┌─────────────────────────────────────┐
        │  echoes_of_the_ashes_db (Postgres) │
        │  - Player data                      │
        │  - Game world state                 │
        └─────────────────────────────────────┘
```

## Updating the PWA

### Update Frontend Only

```bash
# Rebuild and restart PWA
docker-compose up -d --build echoes_of_the_ashes_pwa
```

### Update API Only

```bash
# Rebuild and restart API
docker-compose up -d --build echoes_of_the_ashes_api
```

### Update Both

```bash
docker-compose up -d --build echoes_of_the_ashes_api echoes_of_the_ashes_pwa
```

## Monitoring

### Check Running Containers

```bash
docker ps | grep echoes
```

### View Logs

```bash
# Follow API logs
docker logs -f echoes_of_the_ashes_api

# Follow PWA logs
docker logs -f echoes_of_the_ashes_pwa

# Show last 100 lines
docker logs --tail 100 echoes_of_the_ashes_api
```

### Resource Usage

```bash
docker stats echoes_of_the_ashes_api echoes_of_the_ashes_pwa
```

## Troubleshooting

### PWA Not Loading

1. Check Nginx logs:
   ```bash
   docker logs echoes_of_the_ashes_pwa
   ```

2. Verify Traefik routing:
   ```bash
   docker logs traefik | grep echoesoftheashgame
   ```

3. Test direct container access:
   ```bash
   docker exec echoes_of_the_ashes_pwa ls -la /usr/share/nginx/html
   ```

### API Not Responding

1. Check API logs for errors:
   ```bash
   docker logs echoes_of_the_ashes_api
   ```

2. Verify database connection:
   ```bash
   docker exec echoes_of_the_ashes_api python -c "from bot.database import engine; import asyncio; asyncio.run(engine.connect())"
   ```

3. Test API directly:
   ```bash
   docker exec echoes_of_the_ashes_api curl http://localhost:8000/
   ```

### SSL Certificate Issues

1. Check Traefik certificate resolver:
   ```bash
   docker logs traefik | grep "acme"
   ```

2. Verify DNS is pointing to server:
   ```bash
   dig echoesoftheashgame.patacuack.net
   ```

3. Force certificate renewal:
   ```bash
   # Remove old certificate
   docker exec traefik rm /letsencrypt/acme.json
   # Restart Traefik
   docker restart traefik
   ```

## Security Considerations

1. **JWT Secret**: Use a strong, unique secret key
2. **Password Hashing**: Bcrypt with salt (already implemented)
3. **HTTPS Only**: Traefik redirects HTTP → HTTPS
4. **CORS**: API only allows requests from PWA domain
5. **SQL Injection**: Using SQLAlchemy parameterized queries
6. **Rate Limiting**: Consider adding rate limiting to API endpoints

## Backup

### Database Backup

```bash
docker exec echoes_of_the_ashes_db pg_dump -U $POSTGRES_USER $POSTGRES_DB > backup.sql
```

### Restore Database

```bash
cat backup.sql | docker exec -i echoes_of_the_ashes_db psql -U $POSTGRES_USER $POSTGRES_DB
```

## Performance Optimization

1. **Nginx Caching**: Already configured for static assets
2. **Service Worker**: Caches API responses and images
3. **CDN**: Consider using a CDN for static assets
4. **Database Indexes**: Ensure proper indexes on frequently queried columns
5. **API Response Caching**: Consider Redis for session/cache storage

## Next Steps

- [ ] Set up monitoring (Prometheus + Grafana)
- [ ] Configure automated backups
- [ ] Implement rate limiting
- [ ] Add health check endpoints
- [ ] Set up log aggregation (ELK stack)
- [ ] Configure firewall rules
- [ ] Implement API versioning
- [ ] Add request/response logging
