# Setup: Firebase Functions

**Most is pre-configured.** Functions scaffolded. Just add config and deploy.

---

## ⚠️ CRITICAL: Import Rules

**Functions run on Node.js - you MUST use `/server` imports or your function will crash.**

```typescript
// ✅ CORRECT
import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
import { handleError } from '@donotdev/core/server';

// ❌ WRONG - crashes on deploy
import { getFirestore } from '@donotdev/firebase';
import { handleError } from '@donotdev/core';
```

**Rule:** Always use `/server` suffix for:
- `@donotdev/firebase/server`
- `@donotdev/core/server`
- `@donotdev/utils/server`

---

## CRUD Functions Setup

**One line to register all entity functions:**

```typescript
// functions/src/index.ts
import { initializeApp } from 'firebase-admin/app';
import { createCrudFunctions } from '@donotdev/functions/firebase';
import * as entities from 'entities';

initializeApp();
export const crud = createCrudFunctions(entities);
```

**Result:** Auto-generates `create_products`, `get_products`, `list_products`, `update_products`, `delete_products` for each entity.

**Access control:** Configured via `entity.access` (see SETUP_CRUD.md). All functions use `invoker: 'public'` - security enforced via role-based access in code.

---

## Custom Functions

**When writing custom functions, use `/server` imports:**

```typescript
import { onCall } from 'firebase-functions/v2/https';
import { FUNCTION_CONFIG } from '@donotdev/functions/firebase';
import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
import { handleError } from '@donotdev/core/server';

export const myFunction = onCall(FUNCTION_CONFIG, async (request) => {
  const db = getFirebaseAdminFirestore();
  // Your logic here
  return { data: 'result' };
});
```

---

## Post-Deployment: Cloud Run IAM

**After deploying, you may see `403 Forbidden` on CORS preflight. Fix:**

```bash
# PowerShell
gcloud run services update create-products --region=europe-west1 --no-invoker-iam-check --project=myproject
```

**For all CRUD functions:**
```powershell
$services = @('create-products', 'get-products', 'list-products', 'update-products', 'delete-products');
foreach ($service in $services) {
  gcloud run services update $service --region=europe-west1 --no-invoker-iam-check --project=myproject
}
```

**Why?** Cloud Run blocks unauthenticated OPTIONS (CORS preflight) by default. Your function still validates Firebase Auth - this only allows the preflight to pass.

---

## Function Naming

**Export name (camelCase):**
```typescript
export const getDashboardMetrics = onCall(...);
// Client: httpsCallable(functions, 'getDashboardMetrics')
```

**Operation ID (snake_case):**
```typescript
createBaseFunction(config, handler, 'get_dashboard_metrics')
// Used for logging, rate limiting
```

---

## Environment

```bash
# .env.local (local)
STRIPE_SECRET_KEY=sk_test_...

# .env (production, synced via dndev sync-secrets)
STRIPE_SECRET_KEY=sk_live_...
```

---

**Add functions, get backend. Framework handles the rest.**
