# Grateful Journal Backend API

FastAPI backend for Grateful Journal - a private-first gratitude journaling app.

**Port:** 8001  
**API Docs:** http://localhost:8001/docs

## 📚 Documentation

- **[REFACTORING_SUMMARY.md](./REFACTORING_SUMMARY.md)** — Overview of database schema refactoring
- **[SCHEMA.md](./SCHEMA.md)** — Complete MongoDB schema reference with examples
- **[MIGRATION_GUIDE.md](./MIGRATION_GUIDE.md)** — Step-by-step migration instructions

## Quick Start

### 1. Prerequisites

- MongoDB running on `mongodb://localhost:27017`
- Python 3.9+

See [MongoDB Setup Guide](../docs/MONGODB_SETUP.md) for installation.

### 2. Install & Run

```bash
# Create virtual environment
python3 -m venv venv
source venv/bin/activate  # macOS/Linux

# Install dependencies
pip install -r requirements.txt

# Run API
python main.py
```

API starts on http://0.0.0.0:8001

### 3. Environment Variables

Copy `.env.example` to `.env`. Defaults work for local dev:

```env
MONGODB_URI=mongodb://localhost:27017
MONGODB_DB_NAME=grateful_journal
API_PORT=8001
ENVIRONMENT=development
FRONTEND_URL=http://localhost:8000
```

## Architecture

- **`main.py`** — FastAPI app, CORS, route registration, lifespan events
- **`config.py`** — Settings management (environment variables)
- **`db.py`** — MongoDB connection (singleton pattern)
- **`models.py`** — Pydantic data models (ObjectId support, encryption metadata)
- **`routers/`** — API endpoints
    - `users.py` — User registration, profile updates, deletion
    - `entries.py` — Journal entry CRUD, date filtering

## API Endpoints

### Users

```
POST   /api/users/register              Register user (after Firebase auth)
GET    /api/users/by-email/{email}      Get user by email
PUT    /api/users/update/{user_id}      Update user profile
DELETE /api/users/{user_id}             Delete user & all data
```

### Entries

```
POST   /api/entries/{user_id}                 Create new entry
GET    /api/entries/{user_id}                 List entries (paginated)
GET    /api/entries/{user_id}/{entry_id}      Get single entry
PUT    /api/entries/{user_id}/{entry_id}      Update entry
DELETE /api/entries/{user_id}/{entry_id}      Delete entry
GET    /api/entries/{user_id}/date/{date}     Get entries by date
```

## Authentication

- Frontend authenticates via **Firebase Google Auth**
- User ID is passed in URL path (no token validation yet; implementation depends on frontend requirements)
- Optional: Add Firebase token verification in middleware later

## Development Notes

- **CORS** enabled for `localhost:8000`
- **Async/await** used throughout for scalability
- **Pydantic** models for request/response validation
- **MongoDB** auto-creates collections on first write
