# Cloudflare Integration: Production Deployment Guide

This guide covers deploying the Cloudflare DNS automation system to production.

> **Scope:** dealer-**subdomain** DNS automation in the 4 apex zones only. Custom (dealer-owned) domains do **not** use Cloudflare for SaaS — they use certbot / Let's Encrypt. See [`CUSTOM_DOMAINS.md`](./CUSTOM_DOMAINS.md).

## Pre-Deployment Checklist

Before deploying to production, verify:

- [ ] All tests pass in staging environment
  ```bash
  npm test
  npm run build
  ```
- [ ] Cloudflare credentials acquired and stored securely
- [ ] DNS records verified in Cloudflare dashboard
- [ ] Rollback DNS scenario tested in staging
- [ ] Error monitoring configured (Sentry, Datadog, etc.)
- [ ] Team notified of deployment and features enabled
- [ ] Database migrations applied (cloudflareRecordId field)

## Production Deployment Steps

### 1. Update Production Environment Variables

Set these in your production secret manager (AWS Secrets Manager, Google Secret Manager, Vercel Secrets, etc.):

```bash
# Cloudflare API credentials (from Cloudflare dashboard)
CLOUDFLARE_API_TOKEN=<production_api_token>
CLOUDFLARE_ZONE_ID=<production_zone_id>
SERVER_IP_ADDRESS=<production_server_ip>

# Existing variables (ensure correct for production)
NEXTAUTH_URL=https://myamsoil.com
DATABASE_URL=<production_database_url>
```

**Security Notes:**

- Never store credentials in `.env.local` or commit to git
- Use production-specific API token (not development token)
- Use production server IP address
- Rotate tokens every 90 days
- Enable audit logging in Cloudflare

### 2. Verify Database Migrations

The database schema requires two new fields on the Dealer model:

```sql
-- These are created by Prisma migrations
ALTER TABLE "Dealer" ADD COLUMN "cloudflareRecordId" TEXT;
ALTER TABLE "Dealer" ADD COLUMN "lastPublishedAt" TIMESTAMP;
```

Apply migrations:

```bash
npx prisma migrate deploy
# or if using Vercel/Managed DB:
npx prisma migrate resolve --applied 20251119000000_add_cloudflare_fields
```

### 3. Deploy Code

```bash
# Push to main/production branch
git push origin feature/cloudflare-dns
# Create and merge PR to main

# Or deploy directly with your platform
# Vercel: vercel --prod
# AWS: git push aws main (if using CodeDeploy)
# Docker: docker build && docker push
```

### 4. Monitor First Publishes

After deployment, monitor the first few dealer publishes:

**In application logs:**

```
✓ Creating Cloudflare DNS record
✓ Cloudflare DNS record created successfully
✓ Dealer status updated successfully
```

**In Cloudflare dashboard:**

1. Navigate to **DNS Records**
2. Verify new A records are created with correct:
   - Subdomain name
   - Server IP address
   - Proxied status (orange cloud)

**In application:**

1. Check dealer dashboard
2. Verify subdomain is accessible
3. Check that dealer page loads and displays correctly

### 5. Enable Monitoring Alerts

Set up alerts for these error conditions:

**CloudflareError: Failed to create DNS record**

```
Condition: Log message contains "Failed to create Cloudflare DNS record"
Action: Notify ops team, page on-call engineer
Severity: High
```

**CloudflareError: Rollback failed**

```
Condition: Log message contains "Failed to rollback DNS record - manual cleanup may be required"
Action: Notify ops team immediately, manual intervention needed
Severity: Critical
```

**Example Sentry configuration:**

```python
import sentry_sdk

sentry_sdk.init(
    dsn="https://your-sentry-dsn@sentry.io/project",
    environment="production",
    traces_sample_rate=0.1,
)

# Monitor Cloudflare errors
sentry_sdk.set_tag("component", "cloudflare_dns")
```

## Operations & Maintenance

### Daily Operations

- Monitor publish success rate
- Check for any Cloudflare DNS record creation failures
- Verify subdomain pages are accessible to users

### Weekly Operations

- Review logs for errors or warnings
- Check Cloudflare audit logs for suspicious API activity
- Verify DNS record count matches published dealers

### Monthly Operations

- Review performance metrics
- Audit API token usage
- Plan token rotation (if approaching 90 days)

### Monitoring Queries

**Cloudflare API Success Rate:**

```sql
SELECT
  DATE(created_at) as date,
  COUNT(*) as total_publishes,
  SUM(CASE WHEN cloudflare_success = true THEN 1 ELSE 0 END) as successful,
  ROUND(100.0 * SUM(CASE WHEN cloudflare_success = true THEN 1 ELSE 0 END) / COUNT(*), 2) as success_rate
FROM dealer_publish_events
WHERE created_at >= NOW() - INTERVAL 7 days
GROUP BY DATE(created_at)
ORDER BY date DESC;
```

**DNS Records by Status:**

```sql
SELECT
  status,
  COUNT(*) as record_count
FROM dealer_dns_records
GROUP BY status;
```

## Rollback Plan

If issues occur after deployment, you have several options:

### Option 1: Disable DNS Creation (Code Rollback)

```bash
# Revert to previous version
git revert <commit_hash>
git push origin main

# This will:
# - Stop creating new DNS records
# - Preserve existing DNS records (won't delete)
# - Allow manual cleanup later
```

**Impact:**

- Existing published dealers keep working
- New publishes won't create DNS records
- Manual DNS cleanup needed if records need deletion

### Option 2: Emergency DNS Cleanup

If many records need deletion:

```bash
# Via Cloudflare API (one at a time)
curl -X DELETE "https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{record_id}" \
  -H "Authorization: Bearer {token}" \
  -H "Content-Type: application/json"

# Via Cloudflare Dashboard
# Navigate to DNS Records and delete records manually
```

### Option 3: Disable Publishing Endpoint

```bash
# In code: Return error for all publish attempts
if (process.env.DISABLE_PUBLISHING === 'true') {
  return NextResponse.json(
    { error: 'Publishing temporarily disabled for maintenance' },
    { status: 503 }
  );
}

# Set env variable to trigger emergency shutdown
DISABLE_PUBLISHING=true
```

## Production Performance Considerations

### DNS Record Creation Latency

- Cloudflare API: 100-500ms typically
- Successful: publish completes in <1 second
- Failed: timeout and retry (with user notification)

### Database Updates

- Transaction-safe: All-or-nothing publish
- Rollback implemented: DNS deleted if DB update fails
- No partial states

### ISR Revalidation

- Non-blocking: Doesn't delay publish response
- Graceful degradation: Failure logged but doesn't fail publish
- Cache hit ensures page availability

## DNS Record Lifecycle

### Creation

```
1. Dealer clicks "Publish"
2. DNS record created in Cloudflare (Points subdomain to server IP)
3. Database updated with cloudflareRecordId
4. Status set to 'active'
5. ISR page generated
6. Subdomain live within 30 seconds
```

### Updates

- DNS record rarely updated (subdomain is permanent)
- If IP changes: Manual update via Cloudflare or re-publish

### Deletion

- Not automatic (preserved for SEO, existing links)
- Manual cleanup via Cloudflare dashboard
- Archive records in database (soft delete)

## Disaster Recovery

### Scenario: API Token Compromised

1. Immediately revoke token in Cloudflare dashboard
2. Create new token with same permissions
3. Update production environment variables
4. Restart application servers
5. Monitor for any suspicious DNS record activity
6. Audit Cloudflare logs for unauthorized changes

### Scenario: Database Corruption

If cloudflareRecordId field becomes corrupted:

```sql
-- Emergency cleanup (requires manual approval)
UPDATE "Dealer"
SET cloudflareRecordId = NULL
WHERE cloudflareRecordId NOT IN (
  SELECT id FROM cloudflare_valid_records
);
```

### Scenario: Rate Limiting Hit

If Cloudflare API rate limit exceeded:

1. Temporary backoff: 1 second delay between publishes
2. Queue publish requests: Save to queue, retry after limit resets
3. Contact Cloudflare: Request higher rate limits for production

## Success Metrics

Track these metrics to validate production deployment:

- **DNS Creation Success Rate**: Target >99.5%
- **Publish Response Time**: Target <2 seconds
- **Subdomain Accessibility**: Target 100% within 60 seconds of publish
- **Error Rate**: Target <0.1%
- **Manual Rollbacks**: Target 0 per week

## Post-Deployment Review (24-48 hours)

After deployment, review:

1. ✅ No critical errors in logs
2. ✅ DNS records created successfully
3. ✅ All published subdomains accessible
4. ✅ Monitoring alerts working correctly
5. ✅ Team trained on troubleshooting
6. ✅ Rollback procedures documented and accessible
7. ✅ Performance baseline established

## References

- [Cloudflare Setup Guide](./CLOUDFLARE_SETUP.md)
- [Cloudflare API Reference](https://developers.cloudflare.com/api/)
- [Operations Checklist](./OPERATIONS_CHECKLIST.md)
