# Documentation & Comments - Firebase Implementation

Firebase-specific implementation of the principles defined in [DOCUMENTATION_COMMENTS.md](../core/DOCUMENTATION_COMMENTS.md).

## Philosophy

- **Code First, Comments Second:** A well-named Cloud Function (`onOrderCreated_sendConfirmationEmail`), a clearly typed interface (`OrderDocument`), and a focused Security Rule helper (`isOwner(uid)`) communicate more than any comment. Write Firebase code that does not need explanation before reaching for a comment.
- **Intent Over Mechanics:** Comment *why* a decision was made, not what the Firebase API does. `// Using transaction because stock and order must be atomically consistent` is useful. `// Get document from Firestore` is noise.

## When to Comment in Firebase

- **Security Rule Intent:** Security Rules are often the most-reviewed and least-understood code in a Firebase project. Comment the *intent* of each rule block: `// Only the order owner can read their order details` or `// Admins can update order status, but not the order contents`. Rules are terse by nature -- comments provide the business context.
- **Firestore Data Model Decisions:** Document denormalization decisions and the tradeoffs they encode. `// Customer name is denormalized here to avoid a join on the order list screen. Kept in sync by onUserUpdated trigger.` This connects a non-obvious schema choice to the reason behind it.
- **Trigger Chain Dependencies:** When Cloud Functions form an event chain (order created -> payment processed -> inventory updated -> notification sent), document the chain at the entry point. `// This trigger starts the order fulfillment chain: see onPaymentProcessed and onInventoryUpdated for subsequent steps.` Without this, the next developer sees isolated functions with no visible relationship.
- **Rate Limit and Quota Context:** Document why specific timeouts, batch sizes, or throttling values were chosen. `// Batch size of 500 matches Firestore's maximum batch write limit` or `// 10-second timeout because the Stripe API p99 is ~8s under load` provides essential context for future tuning.
- **TODO with Context:** If you must leave a TODO, include who, why, and a reference. `// TODO(floyd): Migrate to v2 functions after PROJ-456 is complete -- v1 onWrite triggers have a known issue with large documents` is actionable. `// TODO: fix later` is debt that never gets paid.

## Anti-Patterns (Avoid)

- **Redundant Comments on Firebase Calls:** Do not comment obvious Firebase SDK calls. `// Initialize Firestore` above `const db = getFirestore()` or `// Get the document` above `doc.get()` is noise. The API is well-documented -- trust the reader to know the SDK.
- **Commented-Out Functions:** Delete unused Cloud Functions, Security Rules, and Firestore indexes. Do not comment them out. Commented-out triggers are particularly dangerous -- they may appear to provide coverage that does not exist. Git preserves history.
- **Change Log Comments in Rules:** Do not add `// Added by X on Y` or `// Modified for ticket Z` to Security Rules. Git blame provides this information. Inline changelogs in rules go stale and clutter the already-dense rules syntax.
- **Over-Documenting Obvious Rules:** Do not comment `// Check if user is authenticated` above `allow read: if request.auth != null`. The rule is self-explanatory. Save comments for rules with non-obvious business logic or complex conditions.

## Documentation Beyond Comments

- **Security Rules README:** Maintain a `RULES.md` or section in the project README that explains the data model, access control philosophy, and how rules map to user roles. Security Rules syntax is dense -- a prose overview helps new team members understand the access model before reading the rules.
- **Firestore Schema Documentation:** Maintain a schema reference document (or TypeScript interfaces in a shared `models/` directory) that describes every collection, its fields, types, relationships, and the Security Rules governing it. Keep this in sync with the actual schema -- stale schema docs are worse than none.
- **Cloud Function Dependency Map:** For projects with many interconnected triggers, maintain a diagram or markdown document showing the event flow: which Firestore writes trigger which functions, which functions write to which collections, and where external services are called. This is invaluable for debugging and onboarding.
- **Architecture Decision Records (ADRs):** Document significant Firebase architecture decisions (Firestore vs. RTDB for a use case, single vs. multi-region, denormalization strategy, function versioning approach). Store ADRs in `docs/decisions/`. Include the context, decision, alternatives considered, and consequences.
- **Runbooks for Operations:** Maintain runbooks for common operational tasks: restoring Firestore from backup, rotating API keys in Secret Manager, handling a failed deployment rollback, investigating a Cloud Function timeout spike. Store in `docs/runbooks/`.
