# 🚀 Zurich Connect - Deployment Guide

Welcome! This guide will walk you through deploying your Zurich Connect tour booking platform to Vercel. Don't worry if you're not super technical - we'll go step by step together!

---

## 📋 Table of Contents

1. [Before You Start](#before-you-start)
2. [Setting Up Your Database (Neon)](#setting-up-your-database-neon)
3. [Setting Up AWS S3 for Image Storage](#setting-up-aws-s3-for-image-storage)
4. [Setting Up Email Service (Resend)](#setting-up-email-service-resend)
5. [Setting Up Mapbox](#setting-up-mapbox)
6. [Deploying to Vercel](#deploying-to-vercel)
7. [Seeding Your Database](#seeding-your-database)
8. [Testing Your Deployment](#testing-your-deployment)
9. [Troubleshooting](#troubleshooting)

---

## 📦 Before You Start

### What You'll Need:
- The project ZIP file (provided to you)
- A GitHub account (free - sign up at [github.com](https://github.com))
- A Vercel account (free - sign up at [vercel.com](https://vercel.com))
- A Neon account (free - for database hosting)
- An AWS account (for image storage)
- A Resend account (free - for sending emails)
- A Mapbox account (free - for maps)

### Estimated Time:
About 45-60 minutes for first-time setup

---

## 🗄️ Setting Up Your Database (Neon)

Neon is a serverless PostgreSQL database that's perfect for Next.js applications. It offers a generous free tier.

### Step 1: Create a Neon Account

1. Go to [neon.tech](https://neon.tech)
2. Click **"Sign Up"** and create an account (you can use GitHub to sign in)
3. Verify your email if prompted

### Step 2: Create a New Project

1. Once logged in, click **"Create Project"**
2. Fill in the details:
   - **Project Name:** `zurich-connect` (or any name you prefer)
   - **Region:** Choose the region closest to your users (e.g., Europe for European users)
   - **PostgreSQL Version:** Use the default (latest version)
3. Click **"Create Project"**

### Step 3: Get Your Database Connection Strings

After creating the project, Neon will show you connection strings. You need **TWO** different connection strings:

1. **Pooled Connection String** (for queries):
   - Look for the connection string that contains `pooler` or has `?pgbouncer=true`
   - Example: `postgresql://user:password@ep-xxx-pooler.region.aws.neon.tech/neondb?pgbouncer=true`
   - **Save this as:** `DATABASE_URL`

2. **Direct Connection String** (for migrations):
   - This is the standard connection without pooling
   - Example: `postgresql://user:password@ep-xxx.region.aws.neon.tech/neondb`
   - **Save this as:** `DIRECT_DATABASE_URL`

> 💡 **Tip:** Click the copy button next to each connection string and paste them into a text file temporarily. You'll need them later!

### Step 4: Add Schema Parameter (Important!)

Both connection strings need `?schema=public` added to the end. If they already have parameters (like `?pgbouncer=true`), add it with `&`:

- **Pooled:** `postgresql://user:password@ep-xxx-pooler.region.aws.neon.tech/neondb?pgbouncer=true&schema=public`
- **Direct:** `postgresql://user:password@ep-xxx.region.aws.neon.tech/neondb?schema=public`

---

## 📸 Setting Up AWS S3 for Image Storage

AWS S3 (Simple Storage Service) is used to store user-uploaded images like tour photos and profile avatars.

### Step 1: Create an AWS Account

1. Go to [aws.amazon.com](https://aws.amazon.com)
2. Click **"Create an AWS Account"**
3. Follow the signup process (you'll need a credit card, but we'll use free tier services)

### Step 2: Create an S3 Bucket

1. Log into AWS Console
2. In the search bar at the top, type **"S3"** and click on it
3. Click **"Create bucket"**
4. Configure your bucket:
   - **Bucket name:** Choose a unique name (e.g., `zurich-connect-uploads-your-name`)
     - Must be globally unique
     - Use lowercase letters, numbers, and hyphens only
   - **AWS Region:** Choose a region close to your users (e.g., `eu-north-1` for Europe)
   - **Object Ownership:** Select "ACLs enabled" and "Bucket owner preferred"
   - **Block Public Access:** **UNCHECK** "Block all public access"
     - ⚠️ Check the acknowledgment box (this is safe - we need public access for images)
   - Leave other settings as default
5. Click **"Create bucket"**

### Step 3: Configure Bucket CORS

CORS (Cross-Origin Resource Sharing) allows your website to upload files to S3.

1. Click on your newly created bucket
2. Go to the **"Permissions"** tab
3. Scroll down to **"Cross-origin resource sharing (CORS)"**
4. Click **"Edit"**
5. Paste this configuration:

```json
[
  {
    "AllowedHeaders": ["*"],
    "AllowedMethods": ["GET", "PUT", "POST", "DELETE", "HEAD"],
    "AllowedOrigins": ["*"],
    "ExposeHeaders": ["ETag"],
    "MaxAgeSeconds": 3000
  }
]
```

6. Click **"Save changes"**

### Step 4: Create IAM User for Programmatic Access

1. In the AWS Console search bar, type **"IAM"** and click on it
2. In the left sidebar, click **"Users"**
3. Click **"Create user"**
4. Enter a username: `zurich-connect-s3-user`
5. Click **"Next"**
6. Select **"Attach policies directly"**
7. In the search box, type **"S3"** and check **"AmazonS3FullAccess"**
   - (For better security, you can create a custom policy that only gives access to your specific bucket)
8. Click **"Next"**, then **"Create user"**

### Step 5: Create Access Keys

1. Click on the user you just created (`zurich-connect-s3-user`)
2. Go to the **"Security credentials"** tab
3. Scroll down to **"Access keys"** and click **"Create access key"**
4. Select **"Application running outside AWS"**
5. Click **"Next"**, then **"Create access key"**
6. **IMPORTANT:** Copy both keys immediately:
   - **Access key ID** (save as `AWS_PUBLIC_ACCESS_KEY`)
   - **Secret access key** (save as `AWS_SECRET_ACCESS_KEY`)
   - ⚠️ You won't be able to see the secret key again!
7. Click **"Done"**

### Summary - AWS S3 Credentials You Need:

- `AWS_BUCKET_NAME`: Your bucket name (e.g., `zurich-connect-uploads-your-name`)
- `AWS_BUCKET_REGION`: Your bucket region (e.g., `eu-north-1`)
- `AWS_PUBLIC_ACCESS_KEY`: Your access key ID
- `AWS_SECRET_ACCESS_KEY`: Your secret access key

---

## 📧 Setting Up Email Service (Resend)

Resend is used to send emails to users (booking confirmations, notifications, etc.)

### Step 1: Create a Resend Account

1. Go to [resend.com](https://resend.com)
2. Click **"Sign Up"** and create an account
3. Verify your email address

### Step 2: Get Your API Key

1. After logging in, go to **"API Keys"** in the left sidebar
2. Click **"Create API Key"**
3. Give it a name: `Zurich Connect Production`
4. Select permissions: **"Full Access"** or **"Sending access"**
5. Click **"Create"**
6. **Copy the API key immediately** (save as `RESEND_API_KEY`)
   - You won't be able to see it again!

### Step 3: Configure Your Sending Email

For the free tier, you can only send from `onboarding@resend.dev`. 

If you want to use your own domain (e.g., `hello@zurich-connect.com`):
1. Go to **"Domains"** in Resend
2. Click **"Add Domain"**
3. Follow the instructions to verify your domain with DNS records
4. Once verified, use your custom email as `RESEND_FROM_EMAIL`

For now, we'll use:
- `RESEND_FROM_EMAIL`: `onboarding@resend.dev`

---

## 🗺️ Setting Up Mapbox

Mapbox provides interactive maps to show tour locations and meeting points.

### Step 1: Create a Mapbox Account

1. Go to [mapbox.com](https://mapbox.com)
2. Click **"Sign Up"** and create an account
3. Verify your email

### Step 2: Get Your Access Token

1. After logging in, you'll see your **Default public token** on the dashboard
2. Click the copy button to copy it
3. Save this as `NEXT_PUBLIC_MAPBOX_TOKEN`

> 💡 **Note:** The free tier includes 50,000 map loads per month, which is plenty for most use cases!

---

## 🚀 Deploying to Vercel

Now comes the exciting part - deploying your website!

### Step 1: Upload Your Project to GitHub

1. **Extract the ZIP file** you received to a folder on your computer
2. Go to [github.com](https://github.com) and sign in
3. Click the **"+"** icon in the top-right corner
4. Select **"New repository"**
5. Configure your repository:
   - **Repository name:** `zurich-connect`
   - **Visibility:** Choose "Private" (recommended) or "Public"
   - **Do NOT** check "Initialize this repository with a README"
6. Click **"Create repository"**

### Step 2: Upload Your Code

GitHub will show you instructions, but here's an easier way:

1. On the repository page, click **"uploading an existing file"** (in the blue box)
2. Drag and drop **ALL** the files from your extracted folder (NOT the folder itself)
3. Make sure all files are selected including:
   - All folders (src, prisma, public, etc.)
   - All config files (package.json, next.config.ts, etc.)
   - The `.env.example` file
4. Scroll down and click **"Commit changes"**

> ⚠️ **Important:** Do NOT upload any `.env` file with actual credentials!

### Step 3: Create a Vercel Account

1. Go to [vercel.com](https://vercel.com)
2. Click **"Sign Up"**
3. Select **"Continue with GitHub"** (this makes things easier!)
4. Authorize Vercel to access your GitHub account

### Step 4: Import Your Project

1. From your Vercel dashboard, click **"Add New..."** → **"Project"**
2. Find your `zurich-connect` repository in the list
3. Click **"Import"**

### Step 5: Configure Environment Variables

This is the most important step! You need to add all your credentials.

1. Before clicking "Deploy", expand **"Environment Variables"**
2. Add each of the following variables **one by one**:

| Variable Name | Value | Where to Find It |
|--------------|-------|------------------|
| `DATABASE_URL` | Your Neon pooled connection string | From Neon setup (Step 2) |
| `DIRECT_DATABASE_URL` | Your Neon direct connection string | From Neon setup (Step 2) |
| `NEXT_PUBLIC_APP_URL` | Leave empty for now (will update later) | Will add after deployment |
| `NODE_ENV` | `production` | Type this exactly |
| `BETTER_AUTH_SECRET` | Create a random string | See below for generator |
| `AWS_BUCKET_NAME` | Your S3 bucket name | From AWS setup (Step 3) |
| `AWS_BUCKET_REGION` | Your S3 bucket region | From AWS setup (Step 3) |
| `AWS_PUBLIC_ACCESS_KEY` | Your AWS access key ID | From AWS setup (Step 3) |
| `AWS_SECRET_ACCESS_KEY` | Your AWS secret access key | From AWS setup (Step 3) |
| `NEXT_PUBLIC_MAPBOX_TOKEN` | Your Mapbox token | From Mapbox setup (Step 4) |
| `RESEND_API_KEY` | Your Resend API key | From Resend setup (Step 3) |
| `RESEND_FROM_EMAIL` | `onboarding@resend.dev` | Or your verified domain email |

#### Generating BETTER_AUTH_SECRET

Open your terminal or use an online tool:

**Option 1: Terminal (Mac/Linux)**
```bash
openssl rand -base64 32
```

**Option 2: Online Generator**
Go to [randomkeygen.com](https://randomkeygen.com) and use a "CodeIgniter Encryption Key"

### Step 6: Deploy!

1. After adding all environment variables, click **"Deploy"**
2. Wait 2-5 minutes for the build to complete
3. You'll see confetti 🎉 when it's done!

### Step 7: Get Your Website URL

1. Vercel will show you your live website URL (e.g., `https://zurich-connect-xxx.vercel.app`)
2. **Copy this URL**
3. Go to your project **Settings** → **Environment Variables**
4. Find `NEXT_PUBLIC_APP_URL` and update it with your URL
5. Click **"Save"**

### Step 8: Redeploy with Updated URL

1. Go to the **"Deployments"** tab
2. Click the **"⋯"** (three dots) on the most recent deployment
3. Select **"Redeploy"**
4. Click **"Redeploy"** again to confirm

---

## 🌱 Seeding Your Database

Now that your site is deployed, you need to add initial data (tours, users, etc.)

### Method 1: Using Vercel CLI (Recommended)

#### Step 1: Install Vercel CLI

Open your terminal and run:

```bash
npm install -g vercel
```

#### Step 2: Login to Vercel

```bash
vercel login
```

Follow the prompts to authenticate.

#### Step 3: Link Your Project

Navigate to your project folder:

```bash
cd path/to/zurich-connect
```

Link to your Vercel project:

```bash
vercel link
```

Select your project from the list.

#### Step 4: Run Database Migrations

```bash
vercel env pull .env.local
npx prisma migrate deploy
```

#### Step 5: Seed the Database

```bash
npm run seed
```

You should see:
```
🌱 Starting seed...
✅ Created guide users
✅ Created explorer users
✅ Created comprehensive tours
✅ Created tour images
✅ Created bookings
✅ Created reviews
🎉 Seed completed successfully!
```

### Method 2: Using Vercel Dashboard (Alternative)

If you have trouble with the CLI:

1. Go to your Vercel project dashboard
2. Click on **"Settings"** → **"Functions"**
3. Create a new serverless function to run the seed script (this requires some technical knowledge)

Alternatively, you can ask a developer to help run the seed command locally with your production database connection strings.

### What Gets Seeded?

The seed script creates:
- **5 Tour Guides** with different specialties (history, food, nature, photography, family tours)
- **5 Explorer Users** (tourists who can book tours)
- **6 Amazing Tours** including:
  - Historic Old Town Walking Tour
  - Food & Wine Experience
  - Lake Zurich & Alpine Mountain Views
  - Art & Museum Tour
  - Swiss Chocolate Workshop
  - Zurich by Night Photography Tour
- **Tour images** from Unsplash
- **Sample bookings** (past, confirmed, and pending)
- **Customer reviews** with ratings

---

## ✅ Testing Your Deployment

### Step 1: Access Your Website

1. Open your website URL in a browser (e.g., `https://zurich-connect-xxx.vercel.app`)
2. You should see the homepage with the hero section and tour listings

### Step 2: Test Basic Features

1. **Browse Tours:** Click on different tours to see details
2. **Search:** Try the search functionality
3. **Filter:** Use the filter sidebar to filter tours by category, price, etc.

### Step 3: Create an Account

1. Click **"Sign Up"** or **"Get Started"**
2. Create a new account with your email
3. Check that you can log in

### Step 4: Test Booking (Optional)

1. Find a tour you like
2. Click **"Book Now"**
3. Fill in the booking form
4. Submit a booking
5. Check if it appears in your bookings dashboard

### Step 5: Check Guide Dashboard

1. Log out of your explorer account
2. Sign up with a new account
3. In your profile, switch your role to "Guide"
4. Create a test tour to ensure the guide features work

---

## 🔧 Troubleshooting

### Build Failures

**Problem:** Vercel build fails with errors

**Solutions:**
1. Check that all environment variables are set correctly
2. Ensure database connection strings include `?schema=public`
3. Check the build logs in Vercel for specific error messages
4. Make sure the repository has all necessary files

### Database Connection Errors

**Problem:** "Can't reach database server" or connection timeout errors

**Solutions:**
1. Verify your `DATABASE_URL` and `DIRECT_DATABASE_URL` are correct
2. Make sure you're using the pooled connection for `DATABASE_URL`
3. Check that your Neon project is active (not suspended)
4. Ensure the connection strings end with `?schema=public`

### Images Not Uploading

**Problem:** User can't upload profile pictures or tour images

**Solutions:**
1. Verify all AWS credentials are correct in environment variables
2. Check that your S3 bucket has public access enabled
3. Verify CORS configuration in your S3 bucket
4. Make sure the IAM user has proper permissions

### Maps Not Showing

**Problem:** Maps are blank or show error

**Solutions:**
1. Verify your `NEXT_PUBLIC_MAPBOX_TOKEN` is set correctly
2. Check that the token is public (starts with `pk.`)
3. Ensure you haven't exceeded Mapbox free tier limits
4. Check browser console for specific Mapbox errors

### Emails Not Sending

**Problem:** Users don't receive booking confirmations or notifications

**Solutions:**
1. Verify your `RESEND_API_KEY` is correct
2. Check that `RESEND_FROM_EMAIL` is either `onboarding@resend.dev` or a verified domain
3. Check Resend dashboard for sending logs and errors
4. Ensure you haven't exceeded free tier limits (100 emails/day)

### Authentication Issues

**Problem:** Can't sign up or log in

**Solutions:**
1. Verify `BETTER_AUTH_SECRET` is set
2. Ensure `NEXT_PUBLIC_APP_URL` matches your actual Vercel URL
3. Clear browser cookies and try again
4. Check browser console for specific error messages

### Seed Script Fails

**Problem:** `npm run seed` command fails

**Solutions:**
1. Ensure migrations have been run first (`npx prisma migrate deploy`)
2. Check that `DIRECT_DATABASE_URL` is correct
3. Look at the error message to see which part of the seed failed
4. You can comment out parts of the seed script to run it in sections

---

## 📞 Getting Help

If you run into issues not covered here:

1. **Check Vercel Logs:** 
   - Go to your Vercel project → Deployments → Click on the deployment → View Function Logs

2. **Check Database Logs:**
   - Go to Neon dashboard → Your project → Operations → View logs

3. **Browser Console:**
   - Right-click on your website → Inspect → Console tab
   - Look for error messages in red

4. **Documentation:**
   - [Vercel Documentation](https://vercel.com/docs)
   - [Neon Documentation](https://neon.tech/docs)
   - [Next.js Documentation](https://nextjs.org/docs)
   - [Prisma Documentation](https://www.prisma.io/docs)

---

## 🎉 Congratulations!

You've successfully deployed Zurich Connect! Your tour booking platform is now live and ready to help guides and explorers connect in Zurich.

### Next Steps:

1. **Custom Domain:** Consider adding a custom domain in Vercel settings (e.g., `zurich-connect.com`)
2. **Email Domain:** Set up a custom domain in Resend for professional emails
3. **Monitor Usage:** Keep an eye on your usage for Vercel, Neon, AWS, and other services
4. **Regular Backups:** Set up automated database backups in Neon
5. **Analytics:** Consider adding analytics to track website usage
6. **SEO:** Optimize meta tags and add sitemap for better search engine visibility

### Important Notes:

- 🔒 **Never share your environment variables or API keys**
- 💰 **Monitor your AWS usage** to avoid unexpected charges
- 📧 **Verify your domain with Resend** for production email sending
- 🔄 **Regular updates:** Keep your dependencies updated for security
- 💾 **Backups:** Neon provides point-in-time recovery, but consider regular backups

---

**Questions?** Feel free to reach out for support!

**Happy hosting! 🚀**
