# Backend API Integration

For data persistence, scores, or user features, integrate the backend REST API:

## Key Decision Points

- **Simple utilities/calculators**: No API needed, use localStorage only
- **Data persistence**: POST /api/data/:key, GET /api/data/:key with localStorage fallback
- **Games with scores**: POST /api/data/score?visibility=public for public score storage
- **Public scores**: GET /api/public-data/users/:key, GET /api/public-data/:userId/:key
- **Sharing**: POST /api/data/:key/share, DELETE /api/data/:key/share
- **User features**: GET /api/auth/user, handle 401 with redirect to /api/auth/login

## Available APIs

### JSON Data Storage

- **Save JSON data**: POST /api/data/:key with Content-Type: application/json → stores in JSONB column (private by default)
- **Save + publish**: POST /api/data/:key?visibility=public → equivalent to POST then POST /api/data/:key/share {visibility: 'public'}
- **Save + share**: POST /api/data/:key?visibility=shared&sharedWithUsers=123,456 → equivalent to POST then POST /api/data/:key/share {userIds: [123,456]}
- **Load JSON data**: GET /api/data/:key → returns the JSON value directly
- **Update JSON**: PUT /api/data/:key with new JSON body → returns the updated value

### Binary/Raw Data Storage

- **Upload file via form**: POST /api/data/:key with multipart/form-data containing 'file' field → stores binary data
- **Upload public file**: Add visibility=public to FormData before posting
- **Store raw data**: POST /api/data/:key with specific Content-Type (text/markdown, image/png, etc.) → stores raw data
- **Store raw public data**: POST /api/data/:key?visibility=public with Content-Type header → stores with visibility
- **Load binary/raw**: GET /api/data/:key → returns data with original content type

### Form Data (converted to JSON)

- **Form without files**: POST /api/data/:key with multipart/form-data (no file) → form fields become JSON object
- **Nested objects**: user[name]=John&user[age]=25 becomes {"user": {"name": "John", "age": "25"}}
- **Arrays**: tags[]=red&tags[]=blue becomes {"tags": ["red", "blue"]}

### Other Operations

- **Delete data**: DELETE /api/data/:key → returns {success: true}
- **Get metadata**: GET /api/data/:key/metadata → returns {key, visibility, dataType, createdAt, updatedAt}
- **Update metadata**: PATCH /api/data/:key/metadata with {visibility: 'public'} → returns updated metadata

### Public Data Access

- **List users with public key**: GET /api/public-data/users/:key → returns [{userId, email, updatedAt}, ...]
- **Get user's public data**: GET /api/public-data/:userId/:key → returns raw value directly
- **Batch get public data**: POST /api/public-data/batch with {users: [1,2], keys: ["score"]} → returns [{userId, email, key, value, updatedAt}, ...]

### Sharing and Publishing

- **Publish publicly**: POST /api/data/:key/share with {visibility: 'public'} → returns {key, visibility: 'public', updatedAt}
- **Share with specific users**: POST /api/data/:key/share with {userIds: [1,2]} → returns {key, visibility: 'shared', sharedWithUsers, updatedAt}
- **Unpublish/Unshare completely**: DELETE /api/data/:key/share → returns {key, visibility: 'private', updatedAt}
- **Remove specific users from sharing**: DELETE /api/data/:key/share with {userIds: [1,2]} → returns {key, visibility, updatedAt, sharedWithUsers?}

### Shared Data Access

- **Get shared data**: GET /api/shared-data/:userId/:key → returns raw value directly (requires auth, must be in sharedWithUsers)
- **List accessible shared data**: GET /api/shared-data/accessible/:key → returns [{userId, email, updatedAt}, ...]

### User Authentication

- **Check auth**: GET /api/auth/user → returns {id, email, username, display_name} or 401
- **Login**: Redirect to /api/auth/login (no need to implement POST or UI, just redirect to login page). Redirects back to the app after login.
- **Logout**: POST /api/auth/logout → returns {success: true}

### User Profile (for cross-app identification)

- **Get user by ID**: GET /api/users/:id → returns {id, username, display_name}
- **Get user by username**: GET /api/users/username/:username → returns {id, username, display_name}

## Integration Guidelines

- Use standard fetch() calls for API integration
- Always provide localStorage fallback for offline functionality
- Handle auth failures gracefully (401 responses)
- Display user authentication status when relevant
- Add `<div id="auth-status"></div>` to show login/logout status
- Update auth status after successful API calls

## Storage Documentation

Before generating the app, generate a STORAGE.md file that documents the app's specific storage design.
This file should define endpoints, data structures, and offline strategies tailored to the app's requirements.
You can skip this step if the app doesn't require any storage at all (even localStorage).

### Sample STORAGE.md

======BEGIN STORAGE.md======
# Storage Design - Markdown Document Editor

## Data Requirements

- **Local Storage**: Draft content, auto-save cache, current document ID
- **Backend Storage**: Published documents, document index pages, sharing settings
- **Document Management**: Paginated document lists for scalability

## Storage Strategy

### Offline-First Approach
- Primary editing: localStorage for immediate responsiveness
- Backend sync: Save when user publishes or shares
- Document discovery: Load paginated document index from backend

### Data Structures

```json
// Individual document: /api/data/doc-abc123
{
  "title": "Meeting Notes",
  "content": "# Weekly Standup\n\n## Action Items...",
  "createdAt": "2025-01-15T10:30:00Z",
  "lastModified": "2025-01-15T14:20:00Z"
}

// Document index page: /api/data/docs-page-1
{
  "documents": [
    {"id": "doc-abc123", "title": "Meeting Notes", "lastModified": "2025-01-15T14:20:00Z"},
    {"id": "doc-def456", "title": "Project Plan", "lastModified": "2025-01-14T15:30:00Z"}
  ],
  "totalCount": 47,
  "hasNextPage": true
}

// Local storage cache
{
  "currentDocId": "doc-abc123",
  "drafts": {
    "doc-abc123": "# Draft content..."
  }
}
```

### API Endpoints Used

- `GET /api/data/docs-page-1` - Load first page of documents (most recent)
- `GET /api/data/docs-page-N` - Load additional pages as needed
- `GET /api/data/doc-:id` - Load specific document content
- `POST /api/data/doc-:id` - Save document privately
- `PUT /api/data/doc-:id` - Update existing document
- `POST /api/data/doc-:id?visibility=public` - Publish document
- `POST /api/data/doc-:id?visibility=shared&sharedWithUsers=123,456` - Share with users
- `DELETE /api/data/doc-:id` - Delete document

### Authentication Requirements

- Optional - Guest mode allows local editing only
- Required for: Publishing, sharing, accessing shared documents, document sync
- Public features: Browse published documents, view shared documents

## Implementation Notes

- Auto-save drafts to localStorage every 30 seconds
- Paginate document list (20 documents per page)
- Generate unique document IDs (timestamp + random)
- Update document index when creating/deleting documents
- Show sync status and sharing indicators
- Graceful offline editing with clear sync state
======END STORAGE.md======