# API Route Documentation Template

**Purpose:** Every route should have a clear, standardized header explaining what it does.

---

## Documentation Pattern

Use this format above **every route**:

```php
/**
 * {METHOD} /api/{path}
 *
 * {One-line description of what this route does}
 *
 * @auth {None|Admin JWT|Customer JWT|Special Token} (authentication required)
 * @rate_limit {rate_limit_group} (optional description)
 * @permission {specific.permission} (if requires specific permission)
 * @param {param_name} ({required|optional}) {Description}
 * @body {field1, field2, field3} (for POST/PUT)
 * @returns {What is returned}
 * @errors {Common error codes and meanings}
 * @side_effect {Any side effects like emails, webhooks, etc.}
 * @used_by {Who/what uses this endpoint}
 * @security {Important security notes}
 * @compliance {Regulatory/legal requirements}
 */
Route::{method}('{path}', 'Controller@method');
```

---

## Examples (From Completed Files)

### Example 1: Public Endpoint (No Auth)
```php
/**
 * GET /api/health
 *
 * Health check endpoint for load balancers and monitoring
 *
 * @auth None (public endpoint)
 * @returns 200 OK if system is healthy, 503 if degraded
 * @used_by AWS ALB, Kubernetes health probes, uptime monitors
 */
Route::get('health', 'API\MetricsController@healthCheck');
```

### Example 2: Admin Authenticated
```php
/**
 * GET /api/analytics/bookings/{event_id?}
 *
 * Booking analytics dashboard - conversions, abandonment rates, funnel analysis
 *
 * @auth Admin (JWT)
 * @rate_limit analytics (prevents DoS on expensive queries)
 * @param event_id (optional) Filter by specific event, or all events if omitted
 * @returns JSON with booking metrics (conversion rate, avg time to complete, etc.)
 * @used_by Admin dashboard analytics page
 */
Route::get('bookings/{event_id?}', 'API\AnalyticsController@getBookingAnalytics');
```

### Example 3: POST with Body + Permissions
```php
/**
 * POST /api/admin/customers/export
 *
 * Export customer database to CSV with optional filters
 *
 * @auth Admin JWT (required)
 * @permission customers.export (must have specific permission)
 * @rate_limit admin
 * @body filters (optional), format (csv|xlsx), fields (array)
 * @returns CSV file download or 202 Accepted with job ID for async export
 * @errors 403 Forbidden (missing permission), 422 Invalid filters
 * @side_effect Creates export job, sends email when ready (for large exports)
 * @used_by Admin customer management page export button
 * @security PII data - logged for GDPR compliance, expires after 24h
 */
Route::post('customers/export', 'API\CustomerController@exportCustomers')
    ->middleware('admin.permission:customers.export');
```

### Example 4: Security-Critical Endpoint
```php
/**
 * POST /api/seats/hold
 *
 * Hold seats for booking (prevents double-booking, race condition protected)
 *
 * @auth None (public, but session-based)
 * @rate_limit booking.rate.limit (strict - prevents seat hoarding)
 * @body event_id, seat_ids (array), session_id, seat_pricing (custom prices)
 * @returns JSON with hold token, expiry time, held seats details
 * @errors 409 Seats already held/sold, 429 Rate limit exceeded, 422 Validation
 * @used_by Customer booking flow (seat selection page)
 * @security Uses pessimistic locking, holds expire in 15min, audit logged
 * @critical Part of payment flow - must be transactionally safe
 */
Route::post('hold', 'API\SeatController@holdSeats')
    ->middleware(['booking.rate.limit']);
```

---

## Field Descriptions

### @auth
- **None** - Public endpoint, no authentication
- **Admin JWT** - Requires admin JWT token in Authorization header
- **Customer JWT** - Requires customer JWT token
- **Entry Staff** - Requires entry staff authentication
- **Special Token** - Fire marshal tokens, API keys, etc.

### @rate_limit
Specify the rate limit group and why it matters:
- `auth` - Prevents brute force (5 attempts/min)
- `admin` - Standard admin rate limit (60 requests/min)
- `booking.rate.limit` - Strict limit on booking operations (10/min)
- `analytics` - Prevents expensive query DoS (30/min)

### @permission
Required Laravel permission gates (if using permission middleware):
- `customers.export`
- `orders.refund`
- `finance.view_detailed_reports`

### @param
Document path parameters:
```php
@param event_id (required) The event ID to fetch
@param order_id (optional) Filter by order, defaults to all
```

### @body
Document POST/PUT request body fields:
```php
@body email, password (required), remember_me (optional boolean)
```

### @returns
What does the endpoint return:
- `JSON with {...}` - Describe the response structure
- `PDF file download`
- `202 Accepted with job ID` - For async operations
- `200 OK (empty)` - For success with no content

### @errors
Common HTTP error codes and what they mean:
```php
@errors 401 Unauthorized, 403 Forbidden (missing permission),
        422 Validation errors, 429 Rate limit exceeded
```

### @side_effect
Important side effects users should know:
- Sends email
- Triggers webhook
- Invalidates cache
- Creates background job
- Charges payment method

### @used_by
Who/what uses this endpoint:
- Admin dashboard login page
- Customer booking flow
- Fire marshals
- External monitoring tools
- Mobile app

### @security
Important security considerations:
- PII data handling
- GDPR compliance
- Audit logging
- Token expiry
- Rate limiting rationale

### @compliance
Regulatory/legal requirements:
- GDPR Article 17 (Right to Erasure)
- Fire safety regulations
- PCI DSS requirements
- Financial reporting standards

### @critical
Mark endpoints that are business-critical:
- Payment processing
- Booking confirmation
- Seat reservation

---

## Files to Document

### ✅ Completed (2/12)
- [x] `analytics.php` - ✅ DONE
- [x] `admin/auth.php` - ✅ DONE

### 🔄 In Progress (0/10)
- [ ] `booking.php` - Critical (35 routes) - **HIGH PRIORITY**
- [ ] `admin/orders.php` - (30 routes) - **HIGH PRIORITY**
- [ ] `admin/tickets.php` - (45 routes) - **HIGH PRIORITY**

### ⏳ Pending (7/10)
- [ ] `customer.php` - (30 routes)
- [ ] `public.php` - (25 routes)
- [ ] `admin/content.php` - (80 routes) - **LARGEST**
- [ ] `admin/customers.php` - (6 routes) - **QUICK**
- [ ] `admin/events.php` - (18 routes)
- [ ] `admin/financial.php` - (15 routes)
- [ ] `admin/system.php` - (35 routes)

---

## Tips for Fast Documentation

1. **Group similar routes** - Document pattern once, apply to all
2. **Copy-paste-modify** - Use existing docs as templates
3. **Focus on critical info** - Don't over-document obvious routes
4. **Security first** - Always document auth, rate limits, permissions
5. **Use @used_by** - Helps understand business context

---

## Validation Checklist

After documenting each file, verify:
- [ ] Every `Route::` line has a comment above it
- [ ] All auth requirements documented
- [ ] Rate limits specified
- [ ] Security notes for sensitive endpoints
- [ ] Common errors documented
- [ ] Business context clear (@used_by)

---

**Next Steps:**
1. Document `booking.php` next (critical, 35 routes)
2. Then `admin/orders.php` and `admin/tickets.php`
3. Finish remaining 7 files
4. Run final review for consistency

**Estimated Time:** ~30min per file (large), ~10min (small files like admin/customers.php)
