# Custom Domain Implementation Checklist

## Phase 1: Database Setup

### Step 1.1: Create VendorDomain Model
- [ ] Create file: `models/database/vendor_domain.py`
- [ ] Copy model code from `vendor_domain_model.py`
- [ ] Import in `models/database/__init__.py`

### Step 1.2: Update Vendor Model
- [ ] Open `models/database/vendor.py`
- [ ] Add `domains` relationship
- [ ] Add `primary_domain` and `all_domains` properties

### Step 1.3: Create Migration
- [ ] Generate migration: `alembic revision -m "add vendor domains"`
- [ ] Copy upgrade/downgrade code from `migration_vendor_domains.py`
- [ ] Apply migration: `alembic upgrade head`
- [ ] Verify table exists: `psql -c "\d vendor_domains"`

## Phase 2: Configuration

### Step 2.1: Update Settings
- [ ] Open `app/core/config.py`
- [ ] Add `platform_domain = "platform.com"` (change to your actual domain)
- [ ] Add custom domain settings from `config_updates.py`
- [ ] Update `.env` file with new settings

### Step 2.2: Test Settings
```bash
# In Python shell
from app.core.config import settings
print(settings.platform_domain)  # Should print your domain
```

## Phase 3: Middleware Update

### Step 3.1: Backup Current Middleware
```bash
cp middleware/vendor_context.py middleware/vendor_context.py.backup
```

### Step 3.2: Update Middleware
- [ ] Open `middleware/vendor_context.py`
- [ ] Replace with code from `updated_vendor_context.py`
- [ ] Review the three detection methods (custom domain, subdomain, path)
- [ ] Check imports are correct

### Step 3.3: Test Middleware Detection
Create test file `tests/test_vendor_context.py`:
```python
def test_custom_domain_detection():
    # Mock request with custom domain
    request = MockRequest(host="customdomain1.com")
    context = VendorContextManager.detect_vendor_context(request)
    assert context["detection_method"] == "custom_domain"
    assert context["domain"] == "customdomain1.com"

def test_subdomain_detection():
    request = MockRequest(host="vendor1.platform.com")
    context = VendorContextManager.detect_vendor_context(request)
    assert context["detection_method"] == "subdomain"
    assert context["subdomain"] == "vendor1"

def test_path_detection():
    request = MockRequest(host="localhost", path="/vendor/vendor1/")
    context = VendorContextManager.detect_vendor_context(request)
    assert context["detection_method"] == "path"
    assert context["subdomain"] == "vendor1"
```

Run tests:
```bash
pytest tests/test_vendor_context.py -v
```

## Phase 4: Admin API Endpoints

### Step 4.1: Create Vendor Domains Router
- [ ] Create file: `app/api/v1/admin/vendor_domains.py`
- [ ] Copy code from `vendor_domains_api.py`
- [ ] Verify imports work

### Step 4.2: Register Router
Edit `app/api/v1/admin/__init__.py`:
```python
from .vendor_domains import router as vendor_domains_router

# In your admin router setup:
admin_router.include_router(
    vendor_domains_router,
    prefix="/vendors",
    tags=["vendor-domains"]
)
```

### Step 4.3: Test API Endpoints
```bash
# Start server
uvicorn main:app --reload

# Test endpoints (use Postman or curl)
# 1. List vendor domains
curl -H "Authorization: Bearer {admin_token}" \
     http://localhost:8000/api/v1/admin/vendors/1/domains

# 2. Add domain
curl -X POST \
     -H "Authorization: Bearer {admin_token}" \
     -H "Content-Type: application/json" \
     -d '{"vendor_id": 1, "domain": "test.com"}' \
     http://localhost:8000/api/v1/admin/vendors/1/domains
```

## Phase 5: DNS Verification (Optional but Recommended)

### Step 5.1: Install DNS Library
```bash
pip install dnspython
```

### Step 5.2: Test DNS Verification
```python
# In Python shell
import dns.resolver

# Test querying TXT record
answers = dns.resolver.resolve("_wizamart-verify.example.com", "TXT")
for txt in answers:
    print(txt.to_text())
```

## Phase 6: Local Testing

### Step 6.1: Test with /etc/hosts
Edit `/etc/hosts`:
```
127.0.0.1 testdomain1.local
127.0.0.1 testdomain2.local
```

### Step 6.2: Add Test Data
```sql
-- Add test vendor
INSERT INTO vendors (subdomain, name, is_active) 
VALUES ('testvendor', 'Test Vendor', true);

-- Add test domain
INSERT INTO vendor_domains (vendor_id, domain, is_verified, is_active)
VALUES (1, 'testdomain1.local', true, true);
```

### Step 6.3: Test in Browser
```bash
# Start server
uvicorn main:app --reload

# Visit in browser:
# http://testdomain1.local:8000/

# Check logs for:
# "✓ Vendor found via custom domain: testdomain1.local → Test Vendor"
```

## Phase 7: Web Server Configuration

### Step 7.1: Update Nginx Configuration
Edit `/etc/nginx/sites-available/your-site`:
```nginx
server {
    listen 80;
    listen 443 ssl http2;
    
    # Accept ALL domains
    server_name _;
    
    # SSL configuration (update paths)
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;  # CRITICAL: Pass domain to FastAPI
        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;
    }
}
```

### Step 7.2: Test Nginx Config
```bash
sudo nginx -t
sudo systemctl reload nginx
```

## Phase 8: Production Deployment

### Step 8.1: Pre-deployment Checklist
- [ ] All tests passing
- [ ] Database migration applied
- [ ] Configuration updated in production .env
- [ ] Nginx configured to accept all domains
- [ ] SSL certificate strategy decided
- [ ] Monitoring configured
- [ ] Rollback plan ready

### Step 8.2: Deploy
```bash
# 1. Pull latest code
git pull origin main

# 2. Install dependencies
pip install -r requirements.txt

# 3. Run migrations
alembic upgrade head

# 4. Restart application
sudo systemctl restart your-app

# 5. Restart nginx
sudo systemctl reload nginx
```

### Step 8.3: Verify Deployment
```bash
# Test health endpoint
curl https://platform.com/health

# Check logs
tail -f /var/log/your-app/app.log

# Look for:
# "✓ Vendor found via custom domain: ..."
```

## Phase 9: Vendor Setup Process

### Step 9.1: Admin Adds Domain for Vendor
1. Log into admin panel
2. Go to Vendors → Select Vendor → Domains
3. Click "Add Domain"
4. Enter domain: `customdomain1.com`
5. Click Save
6. Copy verification instructions

### Step 9.2: Vendor Configures DNS
Vendor goes to their domain registrar and adds:

**A Record:**
```
Type: A
Name: @
Value: [your server IP]
TTL: 3600
```

**Verification TXT Record:**
```
Type: TXT
Name: _wizamart-verify
Value: [token from step 9.1]
TTL: 3600
```

### Step 9.3: Admin Verifies Domain
1. Wait 5-15 minutes for DNS propagation
2. In admin panel → Click "Verify Domain"
3. System checks DNS for TXT record
4. If found → Domain marked as verified
5. Domain is now active!

### Step 9.4: Test Custom Domain
```bash
# Visit vendor's custom domain
curl https://customdomain1.com/

# Should show vendor's shop
# Check server logs for confirmation
```

## Phase 10: SSL/TLS Setup

### Option A: Let's Encrypt (Per-Domain)
```bash
# For each custom domain
sudo certbot certonly --webroot \
  -w /var/www/html \
  -d customdomain1.com \
  -d www.customdomain1.com

# Auto-renewal
sudo certbot renew --dry-run
```

### Option B: Cloudflare (Recommended)
1. Vendor adds domain to Cloudflare
2. Cloudflare provides SSL automatically
3. Points Cloudflare DNS to your server
4. No server-side certificate needed

### Option C: Wildcard (Subdomains Only)
```bash
# Only for *.platform.com
sudo certbot certonly --dns-cloudflare \
  -d "*.platform.com" \
  -d "platform.com"
```

## Troubleshooting Guide

### Issue: Vendor not detected
**Check:**
```sql
-- Is domain in database?
SELECT * FROM vendor_domains WHERE domain = 'customdomain1.com';

-- Is domain verified?
SELECT * FROM vendor_domains 
WHERE domain = 'customdomain1.com' 
AND is_verified = true 
AND is_active = true;

-- Is vendor active?
SELECT v.* FROM vendors v
JOIN vendor_domains vd ON v.id = vd.vendor_id
WHERE vd.domain = 'customdomain1.com';
```

**Check logs:**
```bash
# Look for middleware debug logs
grep "Vendor context" /var/log/your-app/app.log

# Should see:
# "🏪 Vendor context: Shop Name (subdomain) via custom_domain"
```

### Issue: Wrong vendor loaded
**Check for duplicates:**
```sql
-- Should be no duplicates
SELECT domain, COUNT(*) 
FROM vendor_domains 
GROUP BY domain 
HAVING COUNT(*) > 1;
```

### Issue: DNS verification fails
**Check DNS propagation:**
```bash
# Check if TXT record exists
dig _wizamart-verify.customdomain1.com TXT

# Should show verification token
```

### Issue: SSL certificate error
**Options:**
1. Use Cloudflare (easiest)
2. Get Let's Encrypt certificate for domain
3. Tell vendor to use their own SSL proxy

## Monitoring & Maintenance

### Add Logging
```python
# In middleware
logger.info(
    f"Request received for {host}",
    extra={
        "host": host,
        "vendor_id": vendor.id if vendor else None,
        "detection_method": context.get("detection_method")
    }
)
```

### Monitor Metrics
- [ ] Number of active custom domains
- [ ] Failed domain verifications
- [ ] Traffic per domain
- [ ] SSL certificate expirations

### Regular Maintenance
- [ ] Review unverified domains (> 7 days old)
- [ ] Check SSL certificate status
- [ ] Monitor DNS changes
- [ ] Clean up inactive domains

## Success Criteria

- [ ] Existing subdomain routing still works
- [ ] New custom domains can be added via admin
- [ ] DNS verification works
- [ ] Multiple domains can point to same vendor
- [ ] Middleware correctly identifies vendor
- [ ] All vendor queries properly scoped
- [ ] No security vulnerabilities (domain hijacking prevented)
- [ ] Monitoring in place
- [ ] Documentation updated

## Rollback Plan

If something goes wrong:

1. **Database:**
```bash
alembic downgrade -1  # Rollback migration
```

2. **Code:**
```bash
git checkout HEAD~1  # Revert to previous commit
sudo systemctl restart your-app
```

3. **Middleware:**
```bash
cp middleware/vendor_context.py.backup middleware/vendor_context.py
sudo systemctl restart your-app
```

4. **Nginx:**
```bash
# Restore previous nginx config from backup
sudo cp /etc/nginx/sites-available/your-site.backup /etc/nginx/sites-available/your-site
sudo systemctl reload nginx
```

## Next Steps After Implementation

1. **Create Admin UI**
   - HTML page for domain management
   - Show verification status
   - DNS configuration help

2. **Vendor Dashboard**
   - Let vendors see their domains
   - Domain analytics
   - SSL status

3. **Automation**
   - Auto-verify domains via webhook
   - Auto-provision SSL certificates
   - Auto-renewal monitoring

4. **Documentation**
   - Vendor help docs
   - Admin guide
   - API documentation

5. **Testing**
   - Load testing with multiple domains
   - Security audit
   - Penetration testing

---

**Estimated Implementation Time:**
- Phase 1-4: 4-6 hours (core functionality)
- Phase 5-7: 2-3 hours (testing and deployment)
- Phase 8-10: 2-4 hours (production setup and SSL)

**Total: 1-2 days for full implementation**
