# Deployment Guide

Complete guide to deploying and configuring ThrillWiki.

---

## Prerequisites

- Node.js 18+ and npm/pnpm
- Supabase project (or Lovable Cloud)
- CloudFlare Images account
- Novu Cloud account (optional, for notifications)

---

## Environment Variables

### Frontend (.env)

```bash
# Supabase
VITE_SUPABASE_URL=https://[project-ref].supabase.co
VITE_SUPABASE_ANON_KEY=[anon_key]

# CloudFlare Images
VITE_CLOUDFLARE_ACCOUNT_HASH=[account_hash]

# Novu (optional)
VITE_NOVU_APPLICATION_IDENTIFIER=[app_id]
VITE_NOVU_SOCKET_URL=wss://ws.novu.co
VITE_NOVU_API_URL=https://api.novu.co
```

### Backend (Supabase Secrets)

Set these in Supabase Dashboard → Project Settings → Secrets:

```bash
# CloudFlare Images
CLOUDFLARE_ACCOUNT_ID=[account_id]
CLOUDFLARE_IMAGES_API_TOKEN=[api_token]

# Novu (optional)
NOVU_API_KEY=[api_key]
```

---

## Setup Instructions

### 1. Clone Repository

```bash
git clone https://github.com/your-org/thrillwiki.git
cd thrillwiki
```

### 2. Install Dependencies

```bash
npm install
# or
pnpm install
```

### 3. Configure Environment

```bash
cp .env.example .env
# Edit .env with your values
```

### 4. Database Setup

The database migrations are already applied in Supabase. If setting up a new project:

```bash
# Install Supabase CLI
npm install -g supabase

# Link to your project
supabase link --project-ref [project-ref]

# Push migrations
supabase db push
```

### 5. Deploy Edge Functions

```bash
# Deploy all functions
supabase functions deploy

# Or deploy individually
supabase functions deploy upload-image
supabase functions deploy process-selective-approval
# ... etc
```

### 6. Set Supabase Secrets

```bash
# Via CLI
supabase secrets set CLOUDFLARE_ACCOUNT_ID=[value]
supabase secrets set CLOUDFLARE_IMAGES_API_TOKEN=[value]

# Or via Dashboard
# Project Settings → Secrets → Add Secret
```

### 7. Configure CloudFlare Images

1. Create CloudFlare account
2. Enable Images product
3. Create API token with Images Write permission
4. Get Account ID and Account Hash
5. Configure variants (avatar, banner, card, etc.)

### 8. Configure Novu (Optional)

1. Create Novu Cloud account
2. Create notification templates:
   - content-approved
   - content-rejected
   - moderation-alert
   - review-reply
3. Get API key and Application Identifier
4. Set environment variables

### 9. Build Frontend

```bash
npm run build
```

### 10. Deploy Frontend

**Option A: Lovable (Recommended)**
- Deploy via Lovable interface
- Automatic deployments on git push

**Option B: Vercel**
```bash
npm install -g vercel
vercel --prod
```

**Option C: Netlify**
```bash
npm install -g netlify-cli
netlify deploy --prod
```

---

## Post-Deployment Checklist

### Verify Services

- [ ] Frontend loads without errors
- [ ] Can sign in with password
- [ ] Can sign in with OAuth (Google, Discord)
- [ ] Database queries work
- [ ] Edge functions respond
- [ ] CloudFlare image upload works
- [ ] Notifications send (if enabled)

### Create Admin User

```sql
-- In Supabase SQL Editor
-- 1. Sign up user via UI first
-- 2. Then grant superuser role
INSERT INTO user_roles (user_id, role, granted_by)
VALUES (
  '[user-id-from-auth-users]',
  'superuser',
  '[user-id-from-auth-users]' -- Self-grant for first superuser
);
```

### Configure RLS

Verify Row-Level Security is enabled:

```sql
-- Check RLS status
SELECT tablename, rowsecurity 
FROM pg_tables 
WHERE schemaname = 'public';

-- All should return rowsecurity = true
```

### Test Critical Flows

1. Create test park submission
2. Review in moderation queue
3. Approve submission
4. Verify park appears on site
5. Check version created
6. Test rollback

---

## Domain Configuration

### Custom Domain (Lovable)

1. Go to Project → Settings → Domains
2. Add custom domain
3. Update DNS records:
   - CNAME: www → [lovable-subdomain]
   - A: @ → [lovable-ip]
4. Wait for SSL provisioning

### Custom Domain (Vercel/Netlify)

Follow platform-specific instructions for custom domains.

---

## Monitoring & Logging

### Supabase Monitoring

- **Dashboard**: Monitor database performance
- **Logs**: View edge function logs
- **Analytics**: Track API usage

### Frontend Monitoring

Consider adding:
- **Sentry**: Error tracking
- **PostHog**: Product analytics
- **LogRocket**: Session replay

### Database Monitoring

```sql
-- Active connections
SELECT count(*) FROM pg_stat_activity;

-- Slow queries
SELECT * FROM pg_stat_statements 
WHERE mean_exec_time > 100 
ORDER BY mean_exec_time DESC 
LIMIT 10;

-- Table sizes
SELECT 
  tablename,
  pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) AS size
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;
```

---

## Backup & Recovery

### Database Backups

Supabase Pro automatically backs up:
- Daily backups kept for 7 days
- Point-in-time recovery

Manual backup:

```bash
supabase db dump > backup.sql
```

### Image Backups

CloudFlare Images are automatically backed up by CloudFlare.

To export all image IDs:

```sql
COPY (
  SELECT cloudflare_image_id, cloudflare_image_url 
  FROM (
    SELECT banner_image_id AS cloudflare_image_id, banner_image_url AS cloudflare_image_url FROM parks
    UNION
    SELECT card_image_id, card_image_url FROM parks
    UNION
    SELECT banner_image_id, banner_image_url FROM rides
    UNION
    SELECT card_image_id, card_image_url FROM rides
    -- ... etc
  ) AS images
  WHERE cloudflare_image_id IS NOT NULL
) TO '/tmp/image_ids.csv' WITH CSV HEADER;
```

---

## Scaling Considerations

### Database Optimization

**Indexes:**
- Add indexes for frequently filtered columns
- Add composite indexes for multi-column queries
- Monitor slow query log

**Caching:**
- Use React Query caching aggressively
- Cache static data (entity lists) for 5+ minutes
- Cache dynamic data (moderation queue) for 10-30 seconds

**Partitioning:**
Consider partitioning large tables when:
- `entity_page_views` > 10M rows
- `notification_logs` > 5M rows

### Edge Function Optimization

- Keep functions small and focused
- Use connection pooling for database
- Cache frequently accessed data
- Consider Deno KV for session data

### Frontend Optimization

**Code Splitting:**
```typescript
const AdminDashboard = lazy(() => import('./pages/AdminDashboard'));
```

**Image Optimization:**
- Use CloudFlare variants (thumbnail, card, banner)
- Lazy load images with `loading="lazy"`
- Use AVIF/WebP formats

**Bundle Size:**
- Analyze bundle: `npm run build -- --analyze`
- Target: < 1MB initial bundle
- Lazy load admin pages

---

## Security Checklist

- [ ] RLS enabled on all tables
- [ ] Supabase secrets set (not in .env)
- [ ] CloudFlare API token restricted to Images only
- [ ] MFA required for admin actions
- [ ] Rate limiting enabled on edge functions
- [ ] CORS configured correctly
- [ ] HTTPS enforced
- [ ] Content Security Policy configured
- [ ] XSS protection enabled

---

## Troubleshooting

### Common Issues

**Build fails:**
```bash
# Clear cache and rebuild
rm -rf node_modules .next dist
npm install
npm run build
```

**Edge function 503:**
- Check function logs in Supabase Dashboard
- Verify secrets are set
- Check function timeout (default 60s)

**Image upload fails:**
- Verify CloudFlare credentials
- Check CORS configuration
- Verify account not over quota

**RLS blocking queries:**
- Check if user authenticated
- Verify policy conditions
- Check AAL level (MFA)

---

## Maintenance

### Regular Tasks

**Weekly:**
- [ ] Review error logs
- [ ] Check slow query log
- [ ] Monitor disk usage
- [ ] Review stuck locks in moderation queue

**Monthly:**
- [ ] Update dependencies (`npm update`)
- [ ] Review security advisories
- [ ] Clean up old page views (90+ days)
- [ ] Archive old notification logs

**Quarterly:**
- [ ] Review database performance
- [ ] Optimize indexes
- [ ] Review and update RLS policies
- [ ] Audit user permissions

---

## Rollback Procedure

If deployment fails:

1. **Revert Frontend:**
   ```bash
   git revert HEAD
   git push
   # Or use platform's rollback feature
   ```

2. **Revert Database:**
   ```bash
   supabase db reset # Local only!
   # Production: Restore from backup
   ```

3. **Revert Edge Functions:**
   ```bash
   supabase functions deploy [function-name] --version [previous-version]
   ```

---

## Support

For deployment issues:
- Check documentation: [docs/](./docs/)
- Review logs: Supabase Dashboard → Logs
- Create issue: GitHub Issues
- Contact: [support email]

---

**Last Updated:** 2025-01-20
