# Deployment Guide

This guide covers deployment options for the SchoolCompare Next.js application.

## Deployment Options

### Option 1: Vercel (Recommended for Next.js)

Vercel is the easiest and most optimized platform for Next.js applications.

#### Steps:

1. **Install Vercel CLI**:
   ```bash
   npm install -g vercel
   ```

2. **Login to Vercel**:
   ```bash
   vercel login
   ```

3. **Deploy**:
   ```bash
   vercel --prod
   ```

4. **Configure Environment Variables** in Vercel dashboard:
   - `NEXT_PUBLIC_API_URL`: Your FastAPI endpoint (e.g., `https://api.schoolcompare.co.uk/api`)
   - `FASTAPI_URL`: Same as above for server-side requests

#### Benefits:
- Automatic HTTPS
- Global CDN
- Zero-config deployment
- Automatic preview deployments
- Built-in analytics

---

### Option 2: Docker (Self-hosted)

Deploy using Docker containers for full control.

#### Prerequisites:
- Docker 20+
- Docker Compose 2+

#### Steps:

1. **Build Docker Image**:
   ```bash
   docker build -t schoolcompare-nextjs:latest .
   ```

2. **Run with Docker Compose**:
   ```bash
   # Create .env file with production variables
   echo "NEXT_PUBLIC_API_URL=https://api.schoolcompare.co.uk/api" > .env
   echo "FASTAPI_URL=http://backend:8000/api" >> .env

   # Start services
   docker-compose up -d
   ```

3. **Verify Deployment**:
   ```bash
   curl http://localhost:3000
   ```

#### Environment Variables:
- `NEXT_PUBLIC_API_URL`: Public API endpoint (client-side)
- `FASTAPI_URL`: Internal API endpoint (server-side)
- `NODE_ENV`: `production`

---

### Option 3: PM2 (Node.js Process Manager)

Deploy directly on a Node.js server using PM2.

#### Prerequisites:
- Node.js 24+
- PM2 (`npm install -g pm2`)

#### Steps:

1. **Build Application**:
   ```bash
   npm run build
   ```

2. **Create PM2 Ecosystem File** (`ecosystem.config.js`):
   ```javascript
   module.exports = {
     apps: [{
       name: 'schoolcompare-nextjs',
       script: 'npm',
       args: 'start',
       cwd: '/path/to/nextjs-app',
       instances: 'max',
       exec_mode: 'cluster',
       env: {
         NODE_ENV: 'production',
         PORT: 3000,
         NEXT_PUBLIC_API_URL: 'https://api.schoolcompare.co.uk/api',
         FASTAPI_URL: 'http://localhost:8000/api',
       },
     }],
   };
   ```

3. **Start with PM2**:
   ```bash
   pm2 start ecosystem.config.js
   pm2 save
   pm2 startup
   ```

---

### Option 4: Nginx Reverse Proxy

Use Nginx as a reverse proxy in front of Next.js.

#### Nginx Configuration:

```nginx
server {
    listen 80;
    server_name schoolcompare.co.uk;

    # Redirect to HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name schoolcompare.co.uk;

    # SSL Configuration
    ssl_certificate /etc/ssl/certs/schoolcompare.crt;
    ssl_certificate_key /etc/ssl/private/schoolcompare.key;

    # Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Proxy to Next.js
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # Proxy to FastAPI
    location /api/ {
        proxy_pass http://localhost:8000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # Cache static files
    location /_next/static/ {
        proxy_pass http://localhost:3000;
        add_header Cache-Control "public, max-age=31536000, immutable";
    }
}
```

---

## Pre-Deployment Checklist

- [ ] Run `npm run build` successfully
- [ ] Run `npm test` - all tests pass
- [ ] Environment variables configured
- [ ] FastAPI backend accessible
- [ ] Database migrations applied
- [ ] SSL certificates configured (production)
- [ ] Domain DNS configured
- [ ] Monitoring/logging set up
- [ ] Backup strategy in place

---

## Post-Deployment Verification

1. **Health Check**:
   ```bash
   curl https://schoolcompare.co.uk
   ```

2. **Test Routes**:
   - Home: `https://schoolcompare.co.uk/`
   - School Page: `https://schoolcompare.co.uk/school/100001`
   - Compare: `https://schoolcompare.co.uk/compare`
   - Rankings: `https://schoolcompare.co.uk/rankings`

3. **Check SEO**:
   - Sitemap: `https://schoolcompare.co.uk/sitemap.xml`
   - Robots: `https://schoolcompare.co.uk/robots.txt`

4. **Performance Audit**:
   - Run Lighthouse in Chrome DevTools
   - Target scores: 90+ for Performance, Accessibility, Best Practices, SEO

---

## Monitoring

### Recommended Tools:
- **Vercel Analytics** (if using Vercel)
- **Sentry** for error tracking
- **Google Analytics** for user analytics
- **Uptime Robot** for uptime monitoring

### Health Check Endpoint:
The application automatically serves health data at the root route.

---

## Rollback Procedure

### Vercel:
```bash
vercel rollback
```

### Docker:
```bash
docker-compose down
docker-compose up -d --force-recreate
```

### PM2:
```bash
pm2 stop schoolcompare-nextjs
# Restore previous build
pm2 start schoolcompare-nextjs
```

---

## Troubleshooting

### Issue: API requests failing
- **Solution**: Check `NEXT_PUBLIC_API_URL` and `FASTAPI_URL` environment variables
- **Verify**: FastAPI backend is accessible from Next.js container/server

### Issue: Build fails
- **Solution**: Check Node.js version (requires 24+)
- **Clear cache**: `rm -rf .next node_modules && npm install && npm run build`

### Issue: Slow page loads
- **Solution**: Enable caching in API calls
- **Check**: Network latency to FastAPI backend
- **Verify**: CDN is serving static assets

---

## Security Considerations

- ✅ HTTPS enabled
- ✅ Security headers configured (X-Frame-Options, CSP, etc.)
- ✅ API keys in environment variables (never in code)
- ✅ CORS properly configured
- ✅ Rate limiting on API endpoints
- ✅ Regular security updates
- ✅ Dependency vulnerability scanning

---

## Support

For deployment issues, contact the DevOps team or refer to:
- [Next.js Deployment Docs](https://nextjs.org/docs/deployment)
- [Vercel Documentation](https://vercel.com/docs)
- [Docker Documentation](https://docs.docker.com/)
