# Momira — Server Setup Guide

## Project Overview
- **App**: Momira (QR Event Camera)
- **Stack**: Next.js 16 + Firebase (Auth, Firestore, Storage, Functions) + TailwindCSS v4
- **Firebase Project**: `arimage-f84ba`
- **Domain**: momira.app
- **Node**: v22

---

## Directory Structure
```
httpsonce.film/
├── web/                    # Next.js frontend
│   ├── src/app/           # App Router pages
│   ├── src/components/    # React components
│   ├── src/lib/           # Firebase config, i18n, utils
│   ├── src/hooks/         # Custom hooks
│   ├── next.config.js     # Next.js config
│   └── package.json
├── backend/               # Firebase backend
│   ├── functions/         # Cloud Functions (TypeScript)
│   │   ├── src/           # Source files
│   │   ├── lib/           # Compiled JS (auto-generated)
│   │   └── package.json
│   ├── firebase.json      # Firebase config
│   ├── .firebaserc        # Project alias
│   ├── firestore.rules    # Security rules
│   └── storage.rules      # Storage rules
└── public/                # Static assets
```

---

## Firebase Config
```
Project ID: arimage-f84ba
API Key: AIzaSyCDNYvI5t5za07WCc5R9o4eeVC7hx84M0A
Auth Domain: arimage-f84ba.firebaseapp.com
Storage Bucket: arimage-f84ba.firebasestorage.app
Messaging Sender ID: 85337517437
App ID: 1:85337517437:web:76c7507200d0b00d91b014
Region: us-central1
```

---

## Email (SMTP) Config
```
Host: mail.momira.app
Port: 465 (SSL)
Username: share@momira.app
Password: momira.app
Used for: Event invitations with QR code
```

---

## Setup Script (Linux/Mac)

```bash
#!/bin/bash
set -e

echo "=== Momira Server Setup ==="

# 1. Prerequisites
echo "[1/8] Checking prerequisites..."
command -v node >/dev/null 2>&1 || { echo "Install Node.js 22: curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - && sudo apt install -y nodejs"; exit 1; }
command -v npm >/dev/null 2>&1 || { echo "npm not found"; exit 1; }
command -v git >/dev/null 2>&1 || { echo "Install git: sudo apt install -y git"; exit 1; }

NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 22 ]; then
  echo "Node 22+ required. Current: $(node -v)"
  exit 1
fi

# 2. Install Firebase CLI
echo "[2/8] Installing Firebase CLI..."
npm install -g firebase-tools

# 3. Login to Firebase
echo "[3/8] Firebase login..."
firebase login --no-localhost
# Or use service account:
# export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"

# 4. Clone/Copy project
echo "[4/8] Setting up project..."
cd /opt  # or your preferred directory
# git clone <your-repo-url> momira
# cd momira
# OR if copying files:
# scp -r user@source:/path/to/httpsonce.film /opt/momira

# 5. Install Frontend dependencies
echo "[5/8] Installing frontend dependencies..."
cd web
npm install
cd ..

# 6. Install Backend dependencies
echo "[6/8] Installing backend dependencies..."
cd backend/functions
npm install
cd ../..

# 7. Build & Deploy Functions
echo "[7/8] Deploying Cloud Functions..."
cd backend/functions
npx tsc
cd ..
firebase deploy --only functions
cd ..

# 8. Deploy Firestore & Storage Rules
echo "[8/8] Deploying security rules..."
cd backend
firebase deploy --only firestore:rules,storage:rules
cd ..

echo ""
echo "=== Setup Complete ==="
echo ""
echo "Next steps:"
echo "  1. Run dev server:  cd web && npm run dev"
echo "  2. Build for prod:  cd web && npm run build"
echo "  3. Deploy hosting:  cd backend && firebase deploy --only hosting"
echo "  4. Admin setup:     Go to /admin/setup (first login becomes admin)"
echo ""
```

---

## Quick Commands Reference

### Development
```bash
# Start Next.js dev server (port 3000)
cd web && npm run dev

# Watch TypeScript changes in functions
cd backend/functions && npx tsc --watch
```

### Deployment
```bash
# Deploy everything
cd backend && firebase deploy

# Deploy only functions
cd backend && firebase deploy --only functions

# Deploy only one function
cd backend && firebase deploy --only functions:sendInvite

# Deploy only rules
cd backend && firebase deploy --only firestore:rules,storage:rules

# Deploy only hosting (after building web)
cd web && npm run build
cd ../backend && firebase deploy --only hosting
```

### Admin Setup
1. Start the app (dev or production)
2. Navigate to `/admin/setup`
3. Login with any account
4. Click "Make me admin" — works only once (first admin)
5. After that, go to `/admin` → Users tab to promote others

---

## Environment Notes

### Firebase .firebaserc (backend/)
```json
{
  "projects": {
    "default": "arimage-f84ba"
  }
}
```

### Key Files
| File | Purpose |
|------|---------|
| `web/src/lib/firebase.ts` | Firebase client config |
| `web/src/lib/i18n.ts` | Translations (ar, en, fr) |
| `web/src/components/auth-provider.tsx` | Auth context + isAdmin |
| `backend/functions/src/index.ts` | All Cloud Functions entry |
| `backend/functions/src/audit-invites.ts` | Email invites via SMTP |
| `backend/functions/src/system-config.ts` | System settings CRUD |
| `backend/firestore.rules` | Firestore security rules |
| `backend/storage.rules` | Storage security rules |

### Cloud Functions (deployed)
| Function | Type | Description |
|----------|------|-------------|
| `createEvent` | onCall | Create new event |
| `joinEvent` | onCall | Join as guest |
| `processPhotoUpload` | onCall | Process uploaded photo |
| `reviewPhoto` | onCall | Approve/reject photo |
| `deleteEvent` | onCall | Delete event |
| `getEventAnalytics` | onCall | Event stats |
| `bootstrapAdmin` | onCall | First admin setup |
| `setUserAdmin` | onCall | Promote/demote admin |
| `listUsers` | onCall | List all users |
| `listPayments` | onCall | List payments |
| `sendInvite` | onCall | Send email invite with QR |
| `getSystemConfig` | onCall | Read system config |
| `setSystemConfig` | onCall | Update system config |
| `createCheckoutSession` | onCall | Stripe checkout |
| `stripeWebhook` | HTTP | Stripe webhook |
| `downloadAlbum` | onCall | Download event album |
| `smartCuration` | onCall | AI photo curation |
| `backupEventToDrive` | onCall | Google Drive backup |

### Stripe (configured via /admin → System tab)
- Secret Key: `sk_live_...` or `sk_test_...`
- Publishable Key: `pk_live_...` or `pk_test_...`
- Webhook Secret: `whsec_...`
- Tiers: Basic (149 SAR), Plus (299 SAR), Premium (499 SAR)

---

## Production Deployment (with custom domain)

### Option A: Firebase Hosting
```bash
cd web && npm run build
cd ../backend && firebase deploy --only hosting
# Then connect domain in Firebase Console → Hosting → Add custom domain
```

### Option B: Self-hosted (PM2 + Nginx)
```bash
# Build
cd web && npm run build

# Run with PM2
pm2 start npm --name "momira" -- start -- -p 3000
pm2 save

# Nginx config
cat > /etc/nginx/sites-available/momira.app << 'EOF'
server {
    listen 80;
    server_name momira.app www.momira.app;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name momira.app www.momira.app;

    ssl_certificate /etc/letsencrypt/live/momira.app/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/momira.app/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_cache_bypass $http_upgrade;
    }
}
EOF

ln -s /etc/nginx/sites-available/momira.app /etc/nginx/sites-enabled/
certbot --nginx -d momira.app -d www.momira.app
nginx -t && systemctl reload nginx
```

---

## Claude CLI Usage on Server

```bash
# If Claude CLI is already installed, you can use it for:

# Code changes
claude "fix the bug in web/src/app/admin/page.tsx"

# Deploy
claude "deploy the functions to firebase"

# Debug
claude "check the firebase functions logs for errors"

# Update features
claude "add dark mode toggle to the pricing page"
```

---

## Troubleshooting

| Issue | Solution |
|-------|----------|
| `Not in a Firebase app directory` | Run commands from `backend/` directory |
| CORS errors on Cloud Functions | Functions need IAM `allUsers` invoker permission or use Firestore directly |
| `output: export` error | Removed from next.config.js — app uses SSR |
| Firestore permission denied | Check `firestore.rules`, ensure user has `isAdmin: true` in users doc |
| SMTP email not sending | Verify `mail.momira.app:465` is reachable from Cloud Functions |
