# Documentation & Comments - Supabase Implementation

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

## Philosophy

- **Code First, Comments Second:** A well-named table (`subscription_plans`), a clearly named RLS policy (`users_read_own_profile`), and a focused database function (`calculate_order_total`) communicate more than any comment. Write SQL and Edge Function code that does not need explanation before reaching for a comment.
- **Intent Over Mechanics:** Comment *why* a decision was made, not what the SQL does. `-- Denormalized from user_profiles to avoid join on every order listing query` is useful. `-- Select all orders` above `SELECT * FROM orders` is noise.

## When to Comment in Supabase

- **RLS Policy Intent:** RLS policies are dense and critically important. Comment the business rule each policy implements: `-- Order owners can read their own orders; admins can read all orders`. The SQL syntax (`USING`, `WITH CHECK`) tells you the mechanism; the comment tells you the intent.
- **Denormalization Decisions:** Document why data is duplicated and how it stays in sync. `-- customer_name is denormalized here to avoid a join on the order list screen. Kept in sync by trigger_sync_customer_name on user_profiles.` This connects a non-obvious schema choice to the reason and the maintenance mechanism.
- **Complex Query Logic:** If a database function uses CTEs, window functions, recursive queries, or lateral joins, a brief comment explaining the query strategy helps the next developer modify it confidently. `-- Recursive CTE walks the org hierarchy to find all descendants of the given org_id`.
- **Trigger Chain Dependencies:** When triggers and webhooks form an event chain (order inserted -> trigger validates -> webhook sends email -> Realtime updates client), document the chain at the entry point: `-- This trigger starts the order fulfillment chain. See webhook process-order and trigger_update_inventory for subsequent steps.`
- **PostgreSQL Extension Usage:** When using extensions (`pg_cron`, `pg_trgm`, `unaccent`, `pgcrypto`), document why the extension was chosen and what it enables: `-- Using pg_trgm for fuzzy name search. GIN index enables similarity queries without full-text search overhead.`
- **TODO with Context:** If you must leave a TODO, include who, why, and a reference. `-- TODO(floyd): Replace with materialized view after PROJ-456 ships; current query is too slow for >100k orders` is actionable. `-- TODO: optimize later` is debt that never gets paid.

## Anti-Patterns (Avoid)

- **Redundant SQL Comments:** Do not comment obvious SQL. `-- Create the users table` above `CREATE TABLE users` is noise. `-- Insert a new order` above `INSERT INTO orders` adds nothing. The SQL is its own documentation for standard operations.
- **Commented-Out SQL:** Delete unused migrations, functions, triggers, and RLS policies. Do not comment them out. Commented-out RLS policies are particularly dangerous -- they may appear to provide coverage that does not exist. Git preserves history; the database schema is the present.
- **Change Log Comments in Migrations:** Do not add `-- Added by X on Y` or `-- Modified for ticket Z` to migration files. The migration filename contains the timestamp, and git blame provides author context. Inline changelogs go stale and clutter the SQL.
- **Over-Commenting RLS Policies:** Do not comment `-- Check if user is authenticated` above `USING (auth.uid() IS NOT NULL)`. The policy is self-explanatory. Save comments for policies with non-obvious business logic, complex joins, or surprising access patterns.
- **Excessive Comments on Standard Patterns:** Do not comment standard Supabase patterns like `auth.uid()`, `auth.jwt()`, or `created_at DEFAULT now()`. These are well-documented platform conventions. Comment only when you deviate from the standard pattern or when the business rule behind the pattern is non-obvious.

## Documentation Beyond Comments

- **Schema Documentation:** Maintain a `docs/schema.md` that describes every table, its purpose, key columns, relationships, and the RLS policies governing it. Keep it in sync with migrations. This is the first document a new team member reads to understand the data model.
- **RLS Policy Summary:** Maintain a summary document or table listing every RLS policy, the table it applies to, the operation (SELECT/INSERT/UPDATE/DELETE), and a one-line description of the rule. This serves as a quick-reference access control matrix for the entire application.
- **Edge Function API Documentation:** For each Edge Function, document the expected request format (method, headers, body schema), response format, error codes, and authentication requirements. Keep this in a README within the function directory or in a central API documentation file.
- **Architecture Decision Records (ADRs):** Document significant Supabase architecture decisions (RLS vs. Edge Function authorization, Realtime vs. polling, denormalization strategy, schema organization) in `docs/decisions/`. Include context, decision, alternatives, and consequences.
- **Runbooks for Operations:** Maintain runbooks for common operational tasks: restoring from PITR backup, rotating API keys, handling a failed migration rollback, debugging slow queries, managing connection pool exhaustion. Store in `docs/runbooks/`.
- **Migration Descriptions:** Use descriptive migration filenames that communicate the change: `20260328_add_subscription_status_enum.sql` not `20260328_update.sql`. The filename is the first thing a reviewer sees -- make it count.
