# Cloudflare DNS Automation - Future Enhancements

**Purpose:** Track potential improvements to the Cloudflare subdomain automation system after v1 launch.

**Related Design:** See `docs/plans/2025-01-19-cloudflare-subdomain-automation-design.md` for current implementation.

---

## 1. Custom Domain Automation (CNAME Delegation)

**Current State:** Custom domains are manually configured by admins.

**Enhancement:** Automate custom domain setup for Growth+ tier dealers.

**Approach: CNAME Delegation**

- Dealer enters their custom domain (e.g., `bobsoils.com`)
- System generates instructions: "Add CNAME record pointing `bobsoils.com` to `proxy.acdev3.com`"
- System monitors DNS to verify CNAME exists
- Once verified, add domain to Cloudflare zone
- Generate SSL certificate automatically

**Implementation Considerations:**

- DNS verification polling (check every 5 minutes)
- Email dealer when verification complete
- Handle DNS propagation delays (24-48 hours)
- Provide troubleshooting help for common DNS issues

**Complexity:** Medium-High (DNS verification, email notifications, troubleshooting UI)

---

## 2. Bulk DNS Operations for Existing Dealers

**Current State:** DNS automation only applies to new dealers who publish after implementation.

**Enhancement:** Backfill DNS records for existing dealers.

**Approach:**

- Admin dashboard with "Bulk DNS Creation" tool
- Filter dealers: `status = 'active' AND cloudflareRecordId IS NULL`
- Queue background jobs to create DNS records
- Rate limit to avoid Cloudflare API throttling
- Report success/failure for each dealer

**Implementation Considerations:**

- Background job queue (BullMQ, Inngest, etc.)
- Rate limiting (5-10 requests per second)
- Retry logic for failures
- Admin UI to monitor progress

**Complexity:** Medium (background jobs, rate limiting, admin UI)

---

## 3. Admin Dashboard for DNS Management

**Current State:** DNS records managed only through publish flow; no admin visibility.

**Enhancement:** Admin dashboard to view and manage DNS records.

**Features:**

- List all dealer subdomains + DNS status
- Manually trigger DNS creation/deletion
- View Cloudflare record details
- Test subdomain resolution
- Bulk operations (create, delete, update)
- DNS health monitoring

**Implementation Considerations:**

- Admin-only route: `/admin/dns`
- Permissions: restrict to admin users
- Real-time DNS lookup testing
- Audit log for manual changes

**Complexity:** Medium (admin UI, permissions, audit logging)

---

## 4. Automatic DNS Cleanup on Subscription Cancellation

**Current State:** DNS records persist even if dealer cancels subscription.

**Enhancement:** Automatically remove DNS records when dealer cancels or subscription lapses.

**Approach:**

- Listen for Stripe webhook: `customer.subscription.deleted`
- Queue DNS deletion job
- Delete DNS record from Cloudflare
- Update dealer status to `cancelled`
- Optionally: keep record for 30-day grace period

**Implementation Considerations:**

- Grace period configuration
- Reactivation handling (restore DNS if they renew)
- Archive dealer page for historical records
- Email notification before deletion

**Complexity:** Low-Medium (webhook handling, grace period logic)

---

## 5. Multi-Region DNS Routing

**Current State:** All subdomains point to single server IP.

**Enhancement:** Route traffic to nearest regional server for better performance.

**Approach:**

- Deploy app to multiple regions (US, EU, Asia)
- Use Cloudflare Load Balancing or Geo Steering
- Route dealers to nearest server based on visitor location
- Health checks and automatic failover

**Implementation Considerations:**

- Multi-region deployment infrastructure
- Database replication or CDN for dealer data
- Cloudflare Load Balancing (additional cost)
- Health check endpoints

**Complexity:** High (multi-region infrastructure, deployment complexity)

---

## 6. DNS Change Monitoring and Alerts

**Current State:** No monitoring for unexpected DNS changes.

**Enhancement:** Monitor DNS records and alert on unauthorized changes.

**Features:**

- Periodic DNS lookup verification
- Compare against database records
- Alert if record deleted or modified
- Auto-remediation: recreate if deleted
- Audit log of all DNS changes

**Implementation Considerations:**

- Scheduled job (hourly or daily)
- Alerting system (email, Slack, PagerDuty)
- Auto-remediation policy
- Rate limiting for lookups

**Complexity:** Low-Medium (scheduled jobs, alerting integration)

---

## 7. Subdomain Transfer Between Dealers

**Current State:** Subdomains permanently tied to dealer account.

**Enhancement:** Allow subdomain transfers (e.g., dealer sells business).

**Approach:**

- Transfer request from current dealer
- Approval from new dealer
- Update database: change `userId`
- Update DNS if needed (shouldn't change for subdomains)
- Transfer ISR-generated page

**Implementation Considerations:**

- Transfer approval workflow
- Email notifications
- Audit trail
- Handle edge cases (active subscriptions, custom domains)

**Complexity:** Medium (workflow, approvals, edge cases)

---

## 8. DNS Analytics and Insights

**Current State:** No visibility into subdomain usage or performance.

**Enhancement:** Analytics dashboard showing subdomain traffic and health.

**Features:**

- Requests per subdomain
- Geographic distribution of visitors
- DNS resolution timing
- SSL certificate status
- Cache hit rates (for ISR pages)

**Implementation Considerations:**

- Cloudflare Analytics API integration
- Data aggregation and storage
- Dashboard UI
- Export/reporting functionality

**Complexity:** Medium (analytics integration, dashboard UI)

---

## 9. Preview Environments for Dealer Pages

**Current State:** Dealers can only see their page after publishing.

**Enhancement:** Provide preview URL before publishing.

**Approach:**

- Generate preview URL: `{subdomain}-preview.acdev3.com`
- Create temporary DNS record (auto-expire after 7 days)
- Allow dealers to preview during onboarding
- Delete preview DNS after publish

**Implementation Considerations:**

- Temporary DNS record management
- Auto-cleanup of expired previews
- Preview-specific ISR caching
- Security: ensure only dealer can access preview

**Complexity:** Medium (temporary DNS, auto-cleanup, security)

---

## 10. Cloudflare Page Rules Automation

**Current State:** No automated Page Rules for dealer subdomains.

**Enhancement:** Auto-configure Page Rules for optimization.

**Features:**

- Cache everything (static dealer pages)
- Browser cache TTL optimization
- Security level adjustments
- Email obfuscation
- Automatic HTTPS rewrites

**Implementation Considerations:**

- Cloudflare Page Rules API
- Cost: Page Rules have limits per zone
- Configuration management
- Per-dealer customization options

**Complexity:** Low-Medium (API integration, configuration)

---

## Priority Recommendations

Based on impact and complexity:

**High Priority:**

1. **Automatic DNS Cleanup on Cancellation** - prevents orphaned records
2. **DNS Change Monitoring** - protects against unauthorized changes

**Medium Priority:** 3. **Admin Dashboard for DNS Management** - operational visibility 4. **Bulk DNS Operations** - backfill existing dealers

**Low Priority (Future):** 5. **Custom Domain Automation** - nice-to-have, but manual is acceptable 6. **Preview Environments** - UX improvement, not critical 7. **Multi-Region Routing** - only needed at scale

**Consider Later:**

- DNS Analytics
- Subdomain Transfers
- Page Rules Automation

---

## Notes

- This document should be reviewed quarterly
- Add new enhancements as they're identified
- Move implemented features to `CHANGELOG.md`
- Link to related design documents when implementing
