# Firebase Deployment Guide

This guide will help you deploy VIBN to Firebase Hosting with Firebase Functions.

## Prerequisites

1. Firebase CLI installed: `npm install -g firebase-tools`
2. Firebase project created
3. AlloyDB instance set up
4. Environment variables configured

## Environment Variables Required

Create a `.env.production` file in the `vibn-frontend` directory with:

```bash
# Deployment URL
NEXT_PUBLIC_APP_URL=https://your-app.web.app

# Firebase Admin SDK (Server-side)
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_CLIENT_EMAIL=your-service-account@your-project.iam.gserviceaccount.com
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nYour private key here\n-----END PRIVATE KEY-----\n"

# Firebase Client SDK (Public)
NEXT_PUBLIC_FIREBASE_API_KEY=your-api-key
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your-project.appspot.com
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=123456789
NEXT_PUBLIC_FIREBASE_APP_ID=1:123456789:web:abcdef

# AlloyDB
ALLOYDB_HOST=10.x.x.x
ALLOYDB_PORT=5432
ALLOYDB_DATABASE=vibn
ALLOYDB_USER=postgres
ALLOYDB_PASSWORD=your-secure-password

# AI Providers
GEMINI_API_KEY=your-gemini-api-key
GOOGLE_CLOUD_PROJECT=your-project-id
GOOGLE_CLOUD_LOCATION=us-central1

# GitHub Integration
GITHUB_CLIENT_ID=your-github-oauth-app-client-id
GITHUB_CLIENT_SECRET=your-github-oauth-app-secret
GITHUB_REDIRECT_URI=https://your-app.web.app/api/github/oauth/callback

# V0 Design Integration
V0_API_KEY=your-v0-api-key
```

## Set Firebase Environment Variables

For sensitive variables that shouldn't be in the `.env.production` file, set them as Firebase Functions secrets:

```bash
# Set Firebase secrets for production
firebase functions:secrets:set FIREBASE_PRIVATE_KEY
firebase functions:secrets:set ALLOYDB_PASSWORD
firebase functions:secrets:set GEMINI_API_KEY
firebase functions:secrets:set GITHUB_CLIENT_SECRET
firebase functions:secrets:set V0_API_KEY

# Set public config
firebase functions:config:set app.url="https://your-app.web.app"
```

## Deployment Steps

### 1. Login to Firebase

```bash
firebase login
```

### 2. Initialize Firebase (if not already done)

```bash
firebase init
```

Select:
- Firestore
- Functions
- Hosting
- Storage

### 3. Build the Application

```bash
cd vibn-frontend
npm run build
```

### 4. Deploy Everything

```bash
# Deploy all (functions + hosting + firestore rules + storage rules)
npm run firebase:deploy:all
```

Or deploy individually:

```bash
# Deploy only Firestore rules and storage rules
npm run firebase:deploy:rules

# Deploy only Firestore indexes
npm run firebase:deploy:indexes

# Deploy only functions and hosting
npm run firebase:deploy:app
```

### 5. Verify Deployment

After deployment, visit your Firebase Hosting URL:
- **Hosting URL**: `https://your-project-id.web.app`
- **Custom Domain**: `https://your-custom-domain.com` (if configured)

## Key Changes Made for Production

### API URL Resolution

The app now automatically detects the correct API URL:

1. **Development**: Uses `http://localhost:3000`
2. **Production**: Uses the request origin or `NEXT_PUBLIC_APP_URL` environment variable
3. **Vercel**: Auto-detects using `VERCEL_URL`

This is handled by the `getApiUrl()` utility in `/lib/utils/api-url.ts`.

### Updated Files

The following API routes now use dynamic URL resolution:

- `/api/projects/[projectId]/mvp-checklist/route.ts`
- `/api/projects/[projectId]/timeline-view/route.ts`
- `/api/projects/[projectId]/complete-history/route.ts`
- `/api/projects/[projectId]/plan/intelligent/route.ts`
- `/api/projects/[projectId]/plan/simulate/route.ts`
- `/api/projects/[projectId]/context/route.ts`
- `/api/projects/[projectId]/audit/generate/route.ts`

## Firebase Configuration

The app is configured to run as a Firebase Function via `firebase.json`:

```json
{
  "hosting": {
    "rewrites": [
      {
        "source": "**",
        "function": "nextjsFunc"
      }
    ]
  },
  "functions": [{
    "source": ".",
    "runtime": "nodejs20"
  }]
}
```

## Troubleshooting

### Port 3000 or 8000 References

All hardcoded `localhost:3000` and `localhost:8000` references have been replaced with environment-aware URL resolution.

### Build Failures

If the build fails:

```bash
# Clear Next.js cache
rm -rf .next

# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm install

# Try building again
npm run build
```

### Function Timeout

If your functions timeout, increase the timeout in `firebase.json`:

```json
{
  "functions": [{
    "source": ".",
    "runtime": "nodejs20",
    "timeout": "300s"
  }]
}
```

### Memory Issues

If you encounter memory issues, increase the memory allocation:

```json
{
  "functions": [{
    "source": ".",
    "runtime": "nodejs20",
    "memory": "2GB"
  }]
}
```

## Custom Domain Setup

1. Go to Firebase Console → Hosting
2. Click "Add custom domain"
3. Follow the DNS verification steps
4. Update `NEXT_PUBLIC_APP_URL` and `GITHUB_REDIRECT_URI` to use your custom domain

## Monitoring

- **Firebase Console**: https://console.firebase.google.com
- **Functions Logs**: `firebase functions:log`
- **Hosting Logs**: Available in Firebase Console

## CI/CD with GitHub Actions

Create `.github/workflows/deploy.yml`:

```yaml
name: Deploy to Firebase

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: '20'
      - run: npm install
        working-directory: vibn-frontend
      - run: npm run build
        working-directory: vibn-frontend
      - uses: w9jds/firebase-action@master
        with:
          args: deploy --only hosting,functions
        env:
          FIREBASE_TOKEN: \${{ secrets.FIREBASE_TOKEN }}
```

## Support

For issues, check:
1. Firebase Functions logs
2. Browser console for client-side errors
3. Network tab to debug API calls

