# Firebase integration — main workshop deployment path
Use this guide with the same Connected Event App. The trainer must prepare and rehearse a working baseline before class; this guide does not provision services or supply a complete application.

## 1. Prepare the project and static frontend
Use the trainer-approved Firebase project with billing enabled for Cloud Functions deployment, a supported Node runtime and the current Firebase CLI. Confirm the project ID before any deployment. Create/register a web app in Firebase Console and copy its web configuration into the frontend. The web configuration is not the Gemini secret.
Generate or adapt the AI Studio frontend to static HTML/CSS/JavaScript modules. Place deployable files in public/. Do not put a Node server or source requiring a build directly into Hosting. Exported AI Studio server secrets do not transfer automatically.
From the workshop app directory, use `firebase login`, then `firebase use --add` to select the approved project. Use `firebase init` for Hosting, Functions (JavaScript) and Firestore; preserve existing files when prompted. Choose public/ as the Hosting directory. Record the chosen function region; client and deployed function must match.

## 2. Authentication and Firestore
Enable Google in Authentication → Sign-in methods. Confirm preview, localhost and deployed hostnames as appropriate in authorised domains.
Use the Firebase web SDK with Google sign-in/sign-out. Require a signed-in user before registration.
Use this fixed path: users/{uid}/registrations/community-learning-day.
Fields: nickname (string, 1–80 characters), sessionChoice (morning or afternoon). No extra fields in this core record. Use set/update on the fixed document, not a new random document on each submit.
Publish the supplied firestore.rules. Verify owner reads/writes and denied signed-out/different-user operations using the emulator or rules test environment. A rules file sitting locally is not deployed protection.
Load the document after authentication. Add an onSnapshot listener to observe changes; unsubscribe on sign-out or user change. Check two tabs signed into the same test account. This demonstrates realtime data updates, not token streaming from Gemini.

## 3. Callable Cloud Function
Use the Functions v2 onCall API for askEvent. The callable protocol validates supplied Auth tokens; your handler must reject a missing request.auth. Client code uses httpsCallable from the Firebase Functions SDK, configured for the same region. Do not use plain fetch with an invented callable payload.
Handler responsibilities:
1. Require request.auth; reject with unauthenticated when absent.
2. Validate question as a non-empty trimmed string with a defined length limit (for example 1,000 characters).
3. Supply the current event reference and a short instruction to answer only from it, acknowledging missing details. Treat user text as a question, not instructions to override the reference.
4. Call Gemini using the current supported server SDK and the trainer-verified model/key. Keep registration records out of the model context.
5. Return a small answer object. Translate failures to safe client errors; never expose keys or internal stack traces.

Store the credential using `firebase functions:secrets:set GEMINI_API_KEY`. In the function source use defineSecret('GEMINI_API_KEY'), bind it with the function's secrets option, and read its value only at runtime. Never put the key in public/, Firebase web config or the worksheet. Check current Gemini API key requirements in AI Studio before delivery.
If a server/Admin SDK accesses Firestore, client security rules do not apply; enforce ownership and authorization in server code. The core registration lab uses the web/client SDK.

## 4. Deploy and verify
Check firebase.json contains the correct functions source, Hosting public directory and Firestore rules path. Then, from the workshop app directory, run:
```
firebase deploy --only functions:askEvent,firestore:rules,hosting
```
Inspect the returned function and Hosting URLs. Confirm the Hosting hostname is authorised for Firebase sign-in. The frontend invokes the callable via the SDK; a Hosting rewrite is not required for this architecture.
Open the actual Hosting URL: sign in, save, refresh, observe a record change and ask the real AI helper. Review function logs with the trainer if it fails. A local preview does not satisfy the deployed-app check.

## 5. Reliability and quota exercise
Disable duplicate submission while a request is pending. Limit input/output sizes. Handle rate-limit and service errors with a clear message and bounded retry/backoff. Trigger a labelled simulated quota failure, recover, then make a real request.
Review usage, function scaling limits and monitoring. maxInstances reduces scaling but is neither a per-user request limit nor a guaranteed budget cap. Discuss server-side per-user limits and App Check before wider release. Do not call a five-check workshop app production-ready.

## Alternative: Cloud Run
Retain an AI Studio-generated server app and deploy it to Cloud Run if that architecture is desired. Configure its server secrets and implement Firebase ID token verification in its endpoints. Firebase Auth and Firestore can remain. This is a separate hosting/backend route; the core project does not need both deployments.

## Official references
- https://firebase.google.com/docs/functions/callable
- https://firebase.google.com/docs/functions/config-env
- https://firebase.google.com/docs/hosting/quickstart
- https://firebase.google.com/docs/firestore/security/get-started
- https://ai.google.dev/gemini-api/docs/ai-studio-quickstart
- https://ai.google.dev/gemini-api/docs/api-key
- https://ai.google.dev/gemini-api/docs/aistudio-deploying
