# 🔧 Comprehensive Troubleshooting Guide

This guide covers common issues and their solutions. Use Ctrl+F (Cmd+F on Mac) to search for your specific error.

---

## 🚨 Most Common Issues

### 1. "Build Failed" on Vercel

**Symptoms:**
- Deployment fails during build
- Red error messages in Vercel logs
- Build doesn't complete

**Solutions:**

#### Check 1: Environment Variables Missing
```
→ Go to Vercel Project Settings
→ Click "Environment Variables"
→ Verify ALL variables from QUICK_REFERENCE.md are present
→ Check for typos in variable names
→ Redeploy after adding missing variables
```

#### Check 2: Database Connection Issues
```
→ Ensure DATABASE_URL ends with: ?pgbouncer=true&schema=public
→ Ensure DIRECT_DATABASE_URL ends with: ?schema=public
→ No extra spaces before/after the URLs
→ Copy fresh connection strings from Neon if needed
```

#### Check 3: Node Version Mismatch
```
→ Check Vercel build logs for Node version errors
→ Add to project settings if needed (usually auto-detected)
→ Supported versions: Node 18.x or 20.x
```

---

### 2. Database Connection Errors

**Error Messages:**
- "Can't reach database server"
- "Connection timeout"
- "Invalid connection string"
- "Database does not exist"

**Solutions:**

#### For Neon Database:

**Check 1: Connection String Format**
```
❌ WRONG:
postgresql://user:pass@host-pooler/db

✅ CORRECT (DATABASE_URL):
postgresql://user:pass@host-pooler/db?pgbouncer=true&schema=public

✅ CORRECT (DIRECT_DATABASE_URL):
postgresql://user:pass@host/db?schema=public
```

**Check 2: Database is Active**
```
→ Go to Neon Console: console.neon.tech
→ Check if project is active (not suspended)
→ Free tier databases can be suspended if inactive
→ Click "Resume" if suspended
```

**Check 3: Network Issues**
```
→ Neon should be accessible from anywhere
→ Check Neon status page: status.neon.tech
→ Try connection string in a database client like TablePlus or DBeaver
```

**Check 4: Credentials**
```
→ Password might contain special characters that need URL encoding
→ Get fresh connection strings from Neon dashboard
→ Replace old ones in Vercel
```

---

### 3. Images Won't Upload / Display

**Symptoms:**
- Profile pictures won't upload
- Tour images show broken image icons
- Upload button doesn't work
- Console errors about S3

**Solutions:**

#### Check 1: AWS Credentials
```
In Vercel Environment Variables, verify:
→ AWS_BUCKET_NAME is correct (no typos)
→ AWS_BUCKET_REGION matches your bucket region
→ AWS_PUBLIC_ACCESS_KEY is complete
→ AWS_SECRET_ACCESS_KEY is complete
→ No extra spaces at start/end of values
```

#### Check 2: S3 Bucket Public Access
```
→ Go to AWS S3 Console
→ Click your bucket
→ Go to "Permissions" tab
→ "Block public access" should show "Off" for:
   • Block public access to buckets and objects granted through new access control lists (ACLs)
   • Block public access to buckets and objects granted through any access control lists (ACLs)
```

#### Check 3: S3 CORS Configuration
```
→ Go to bucket → Permissions → CORS
→ Should have configuration allowing:
   • AllowedMethods: GET, PUT, POST, DELETE, HEAD
   • AllowedOrigins: *
   • AllowedHeaders: *

If missing, add this config:
[
  {
    "AllowedHeaders": ["*"],
    "AllowedMethods": ["GET", "PUT", "POST", "DELETE", "HEAD"],
    "AllowedOrigins": ["*"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 3000
  }
]
```

#### Check 4: IAM User Permissions
```
→ Go to AWS IAM Console
→ Users → zurich-connect-s3-user
→ Permissions tab
→ Should have "AmazonS3FullAccess" policy
→ If not, click "Add permissions" → "Attach policies"
→ Search for "AmazonS3FullAccess" and attach
```

#### Check 5: Browser Console Errors
```
→ Open browser DevTools (F12)
→ Go to Console tab
→ Look for S3-related errors
→ Common issues:
   • CORS error → Fix CORS config
   • 403 Forbidden → Fix permissions
   • 404 Not Found → Check bucket name
```

---

### 4. Maps Not Displaying

**Symptoms:**
- Gray box where map should be
- "Error loading map" message
- Map tiles don't load

**Solutions:**

#### Check 1: Mapbox Token
```
→ Verify NEXT_PUBLIC_MAPBOX_TOKEN is set in Vercel
→ Token should start with "pk."
→ Get fresh token from mapbox.com if needed
→ Ensure it's a PUBLIC token, not a secret token
```

#### Check 2: Token Validity
```
→ Go to account.mapbox.com/access-tokens/
→ Check if token is active (not revoked)
→ Check token restrictions (should allow your domain)
→ Create new token if current one has issues
```

#### Check 3: Usage Limits
```
→ Free tier: 50,000 map loads/month
→ Check usage at account.mapbox.com
→ If exceeded, upgrade plan or wait for reset
```

#### Check 4: Browser Errors
```
→ Open DevTools (F12) → Console
→ Look for Mapbox errors
→ Common: "Unauthorized" → Bad token
→ "Forbidden" → Token restrictions
```

---

### 5. Emails Not Sending

**Symptoms:**
- No booking confirmation emails
- No welcome emails
- Email errors in logs

**Solutions:**

#### Check 1: Resend API Key
```
→ Verify RESEND_API_KEY in Vercel env variables
→ Should start with "re_"
→ No extra spaces before/after
→ Get fresh key from resend.com/api-keys if needed
```

#### Check 2: Sender Email Address
```
→ RESEND_FROM_EMAIL should be:
   • "onboarding@resend.dev" (free tier)
   • OR your verified domain email

→ If using custom domain:
   • Must be verified in Resend dashboard
   • Check DNS records are correct
   • Allow 24-48 hours for DNS propagation
```

#### Check 3: Resend Dashboard
```
→ Go to resend.com/logs
→ Check for:
   • Failed sends (see error messages)
   • Rate limits (100/day on free tier)
   • Blocked sends
→ Review specific error messages
```

#### Check 4: Email in Spam
```
→ Check spam/junk folder
→ Especially common with onboarding@resend.dev
→ Custom domain reduces spam risk
```

---

### 6. Authentication Issues

**Symptoms:**
- Can't sign up
- Can't log in
- "Invalid session" errors
- Redirected back to login

**Solutions:**

#### Check 1: BETTER_AUTH_SECRET
```
→ Verify it's set in Vercel
→ Should be a long random string (32+ characters)
→ Generate new one if needed:
   openssl rand -base64 32
```

#### Check 2: NEXT_PUBLIC_APP_URL
```
→ Must match your actual Vercel URL EXACTLY
→ Should include https://
→ No trailing slash at the end
→ Example: https://zurich-connect-abc123.vercel.app

→ Update in Vercel → Settings → Environment Variables
→ Redeploy after changing
```

#### Check 3: Clear Browser Data
```
→ Clear cookies for your site
→ Clear browser cache
→ Try incognito/private browsing mode
→ Try different browser
```

#### Check 4: Check Database
```
→ Verify user table exists in database
→ Check if migrations were run:
   npx prisma migrate deploy
```

---

### 7. 404 Errors / Page Not Found

**Symptoms:**
- Pages return 404
- Routes don't work
- "This page could not be found"

**Solutions:**

#### Check 1: Deployment Completed
```
→ Go to Vercel Deployments
→ Ensure latest deployment shows "Ready"
→ Not "Building" or "Error"
→ Redeploy if needed
```

#### Check 2: Build Output
```
→ Check Vercel build logs
→ Look for "Build Error" messages
→ Ensure all pages built successfully
```

#### Check 3: Route Name
```
→ URLs are case-sensitive
→ Check spelling
→ Try going to homepage first, then navigating
```

---

### 8. Slow Performance

**Symptoms:**
- Pages load slowly
- Images take long to load
- Database queries timeout

**Solutions:**

#### Check 1: Database Connection
```
→ Ensure using DATABASE_URL (pooled) for queries
→ Not DIRECT_DATABASE_URL
→ Pooled connection is faster
```

#### Check 2: Image Optimization
```
→ Images should be served from S3
→ Check if Next.js Image component is used
→ Optimize large images before upload
```

#### Check 3: Vercel Region
```
→ Check Vercel deployment region
→ Should be close to your users
→ Can't change after deployment without redeploying
```

#### Check 4: Free Tier Limitations
```
→ Free tiers have performance limits
→ Consider upgrading for production traffic
→ Monitor usage in dashboards
```

---

### 9. Seed Data Not Showing

**Symptoms:**
- No tours on homepage
- Empty database
- "No results found"

**Solutions:**

#### Check 1: Seed Script Ran Successfully
```
→ Did you see all success messages?
   ✅ Created guide users
   ✅ Created explorer users
   ✅ Created comprehensive tours
   ✅ Created tour images
   ✅ Created bookings
   ✅ Created reviews
   🎉 Seed completed successfully!

→ If not, run again:
   npm run seed
```

#### Check 2: Database Connection for Seeding
```
→ Ensure .env.local has DIRECT_DATABASE_URL
→ Run: vercel env pull .env.local
→ Then: npm run seed
```

#### Check 3: Migrations
```
→ Run migrations first:
   npx prisma migrate deploy
→ Then seed:
   npm run seed
```

#### Check 4: Check Database Directly
```
→ Use Prisma Studio:
   npx prisma studio
→ Or check Neon dashboard
→ See if tables have data
```

---

### 10. Build Warnings

**Symptoms:**
- Yellow warnings in build logs
- "Deprecated" messages
- TypeScript errors

**Solutions:**

#### Generally Safe to Ignore:
```
→ Deprecation warnings (won't stop deployment)
→ Experimental feature warnings
→ Some TypeScript type warnings
```

#### Should Fix:
```
→ Security vulnerabilities
→ Missing dependencies
→ TypeScript errors (red, not yellow)
```

#### How to Fix:
```
→ Most warnings won't stop deployment
→ Document them for future updates
→ Update dependencies if security-related
```

---

## 🔍 How to Debug

### Method 1: Vercel Logs
```
1. Go to Vercel Dashboard
2. Click your project
3. Click "Deployments"
4. Click on latest deployment
5. Click "View Function Logs"
6. Look for error messages in red
```

### Method 2: Browser Console
```
1. Right-click on page
2. Click "Inspect" or "Inspect Element"
3. Click "Console" tab
4. Look for red error messages
5. Note the error type and message
```

### Method 3: Network Tab
```
1. Open DevTools (F12)
2. Click "Network" tab
3. Reload page
4. Look for failed requests (red)
5. Click failed request to see details
```

### Method 4: Database Logs
```
1. Go to Neon Console
2. Click your project
3. Click "Operations" tab
4. View query logs
5. Look for failed queries
```

---

## 📞 Getting More Help

### Before Asking for Help:

1. **Gather Information:**
   - What were you trying to do?
   - What did you expect to happen?
   - What actually happened?
   - Any error messages? (copy exact text)
   - What have you tried already?

2. **Check These First:**
   - All environment variables are set
   - Database connection strings are correct
   - AWS credentials are valid
   - API keys haven't expired
   - Service status pages (Vercel, Neon, AWS)

3. **Useful Information to Share:**
   - Browser and version
   - Operating system
   - Error messages (full text)
   - Screenshots of errors
   - Vercel build logs (if build issue)
   - Steps to reproduce the problem

### Service Status Pages:
- **Vercel:** https://www.vercel-status.com/
- **Neon:** https://status.neon.tech/
- **AWS:** https://status.aws.amazon.com/
- **Resend:** https://status.resend.com/
- **Mapbox:** https://status.mapbox.com/

---

## 🎯 Quick Fixes Summary

| Issue | Quick Fix |
|-------|-----------|
| Build fails | Check env variables in Vercel |
| Database error | Verify connection string format |
| Images broken | Check AWS credentials & CORS |
| Maps not showing | Verify Mapbox token |
| No emails | Check Resend API key |
| Can't log in | Clear cookies, check NEXT_PUBLIC_APP_URL |
| 404 errors | Ensure deployment completed |
| No tours showing | Run seed script |
| Slow site | Use DATABASE_URL (pooled) |

---

## 💡 Prevention Tips

1. **Double-check before saving**
   - No spaces at start/end of env variables
   - Copy values completely
   - Check for typos

2. **Test incrementally**
   - Don't wait until everything is set up
   - Test after each major step
   - Fix issues as they arise

3. **Keep credentials safe**
   - Use password manager
   - Never commit to Git
   - Rotate keys if exposed

4. **Monitor regularly**
   - Check dashboards weekly
   - Watch for unusual activity
   - Monitor costs

5. **Document changes**
   - Note any custom modifications
   - Keep track of settings
   - Document solutions to problems

---

**Still stuck? Review the detailed DEPLOYMENT_GUIDE.md or reach out for support!**
