# Meditation Content API

This document provides comprehensive documentation for the Lilith Content
Service Meditation API, including CRUD operations, filtering, search,
versioning, and localization.

## Overview

The Meditation Content API enables management of meditation content with:

- **CRUD Operations**: Full create, read, update, delete for meditations
- **Advanced Filtering**: Filter by type, focus, difficulty, duration,
  instructor, time of day
- **Tag Search**: Search by tags with match-all or match-any logic
- **Status Workflow**: Draft → Review → Published → Archived workflow
- **Versioning**: Version history with snapshots and rollback
- **Localization**: Multi-language support with translation tracking
- **Engagement Metrics**: Play count, completion, ratings, favorites

---

## Table of Contents

1. [Types and Enums](#types-and-enums)
2. [CRUD Operations](#crud-operations)
3. [Filtering Endpoints](#filtering-endpoints)
4. [Status Workflow](#status-workflow)
5. [Versioning](#versioning)
6. [Localization](#localization)
7. [Engagement Metrics](#engagement-metrics)
8. [Error Handling](#error-handling)

---

## Types and Enums

### Meditation Types

| Type              | Description                                    |
| ----------------- | ---------------------------------------------- |
| `guided`          | Instructor-led meditation with verbal guidance |
| `unguided`        | Silent or ambient meditation                   |
| `breathing`       | Breath-focused exercises                       |
| `body_scan`       | Progressive body awareness practice            |
| `visualization`   | Guided imagery meditation                      |
| `mantra`          | Repetition-based meditation                    |
| `loving_kindness` | Compassion-focused practice                    |
| `mindfulness`     | Present-moment awareness                       |
| `sleep`           | Sleep-inducing meditation                      |
| `walking`         | Movement-based meditation                      |
| `movement`        | Dynamic movement practice                      |

### Focus Areas

| Focus              | Description                  |
| ------------------ | ---------------------------- |
| `stress`           | Stress relief and relaxation |
| `anxiety`          | Anxiety reduction            |
| `sleep`            | Better sleep quality         |
| `focus`            | Improved concentration       |
| `self_compassion`  | Self-acceptance practices    |
| `gratitude`        | Gratitude cultivation        |
| `relationships`    | Relationship improvement     |
| `creativity`       | Creative enhancement         |
| `energy`           | Energy and vitality          |
| `healing`          | Physical/emotional healing   |
| `spiritual_growth` | Spiritual development        |
| `general`          | General well-being           |

### Difficulty Levels

| Level          | Description               |
| -------------- | ------------------------- |
| `beginner`     | New to meditation         |
| `intermediate` | Some experience           |
| `advanced`     | Experienced practitioners |

### Time of Day Recommendations

| Time           | Description        |
| -------------- | ------------------ |
| `morning`      | Morning practice   |
| `afternoon`    | Midday practice    |
| `evening`      | Evening practice   |
| `before_sleep` | Pre-sleep practice |

### Duration Ranges

| Range    | Minutes   |
| -------- | --------- |
| Quick    | 1-5 min   |
| Short    | 5-10 min  |
| Medium   | 10-20 min |
| Long     | 20-45 min |
| Extended | 45+ min   |

### Meditation Object

```json
{
  "id": "uuid",
  "slug": "morning-breath-awareness",
  "title": "Morning Breath Awareness",
  "description": "Start your day with mindful breathing",
  "introduction": "Welcome to this morning practice...",
  "type": "breathing",
  "focus": "focus",
  "durationMinutes": 10,
  "difficulty": "beginner",
  "audioUrl": "https://cdn.lilith.app/audio/morning-breath.mp3",
  "videoUrl": null,
  "thumbnailUrl": "https://cdn.lilith.app/thumbnails/morning-breath.jpg",
  "backgroundMusicUrl": "https://cdn.lilith.app/music/ambient-1.mp3",
  "mediaAssetId": "uuid",
  "instructorId": "uuid",
  "instructorName": "Sarah Chen",
  "instructorVoiceStyle": "calm, nurturing",
  "categoryId": "uuid",
  "tags": ["morning", "beginner-friendly", "short"],
  "benefits": ["improved focus", "reduced stress", "mental clarity"],
  "recommendedTimes": ["morning"],
  "isPremium": false,
  "isFree": true,
  "status": "published",
  "publishedAt": "2024-01-01T00:00:00.000Z",
  "playCount": 5000,
  "completionCount": 4200,
  "averageRating": 4.8,
  "ratingCount": 350,
  "favoriteCount": 1200,
  "sortOrder": 1,
  "locale": "en",
  "availableLocales": ["en", "es", "fr"],
  "deletedAt": null,
  "createdAt": "2024-01-01T00:00:00.000Z",
  "updatedAt": "2024-01-01T00:00:00.000Z"
}
```

---

## CRUD Operations

### Create Meditation

Create a new meditation.

**Endpoint:** `POST /v1/meditations`

**Request Body:**

| Field                  | Type     | Required | Description                          |
| ---------------------- | -------- | -------- | ------------------------------------ |
| `slug`                 | string   | Yes      | URL-friendly identifier              |
| `title`                | string   | Yes      | Meditation title                     |
| `durationMinutes`      | integer  | Yes      | Duration in minutes                  |
| `description`          | string   | No       | Full description                     |
| `introduction`         | string   | No       | Introduction text                    |
| `type`                 | string   | No       | Meditation type (default: guided)    |
| `focus`                | string   | No       | Focus area (default: general)        |
| `difficulty`           | string   | No       | Difficulty level (default: beginner) |
| `audioUrl`             | string   | No       | Primary audio URL                    |
| `videoUrl`             | string   | No       | Video URL                            |
| `thumbnailUrl`         | string   | No       | Thumbnail image URL                  |
| `backgroundMusicUrl`   | string   | No       | Background music URL                 |
| `mediaAssetId`         | uuid     | No       | Reference to media asset             |
| `instructorId`         | uuid     | No       | Instructor user ID                   |
| `instructorName`       | string   | No       | Instructor display name              |
| `instructorVoiceStyle` | string   | No       | Voice description                    |
| `categoryId`           | uuid     | No       | Category ID                          |
| `tags`                 | string[] | No       | Tags for categorization              |
| `benefits`             | string[] | No       | List of benefits                     |
| `recommendedTimes`     | string[] | No       | Recommended times of day             |
| `isPremium`            | boolean  | No       | Premium content flag                 |
| `isFree`               | boolean  | No       | Free content flag                    |
| `sortOrder`            | integer  | No       | Display order                        |
| `locale`               | string   | No       | Primary locale                       |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/meditations" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "slug": "morning-breath-awareness",
    "title": "Morning Breath Awareness",
    "description": "Start your day with mindful breathing",
    "type": "breathing",
    "focus": "focus",
    "durationMinutes": 10,
    "difficulty": "beginner",
    "audioUrl": "https://cdn.lilith.app/audio/morning-breath.mp3",
    "instructorName": "Sarah Chen",
    "tags": ["morning", "beginner-friendly"],
    "benefits": ["improved focus", "reduced stress"],
    "recommendedTimes": ["morning"],
    "isFree": true
  }'
```

**Response (201 Created):**

```json
{
  "id": "meditation_abc123",
  "slug": "morning-breath-awareness",
  "title": "Morning Breath Awareness",
  "type": "breathing",
  "focus": "focus",
  "durationMinutes": 10,
  "difficulty": "beginner",
  "status": "draft",
  "playCount": 0,
  "completionCount": 0,
  "averageRating": null,
  "ratingCount": 0,
  "favoriteCount": 0,
  "createdAt": "2024-01-01T00:00:00.000Z",
  "updatedAt": "2024-01-01T00:00:00.000Z"
}
```

### List Meditations

Retrieve meditations with filtering and pagination.

**Endpoint:** `GET /v1/meditations`

**Query Parameters:**

| Parameter         | Type    | Description                            |
| ----------------- | ------- | -------------------------------------- |
| `status`          | string  | Filter by status                       |
| `type`            | string  | Filter by meditation type              |
| `focus`           | string  | Filter by focus area                   |
| `difficulty`      | string  | Filter by difficulty                   |
| `categoryId`      | uuid    | Filter by category                     |
| `instructorId`    | uuid    | Filter by instructor                   |
| `isPremium`       | boolean | Filter premium content                 |
| `isFree`          | boolean | Filter free content                    |
| `minDuration`     | integer | Minimum duration in minutes            |
| `maxDuration`     | integer | Maximum duration in minutes            |
| `tags`            | string  | Comma-separated tags                   |
| `recommendedTime` | string  | Filter by recommended time             |
| `search`          | string  | Full-text search query                 |
| `page`            | integer | Page number (default: 1)               |
| `limit`           | integer | Items per page (max: 100, default: 20) |
| `sortBy`          | string  | Sort field (default: created_at)       |
| `sortOrder`       | string  | `asc` or `desc` (default: desc)        |

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/meditations?type=breathing&difficulty=beginner&limit=10" \
  -H "Authorization: Bearer <access_token>"
```

**Response:**

```json
{
  "items": [
    {
      "id": "meditation_abc123",
      "title": "Morning Breath Awareness",
      "type": "breathing",
      "durationMinutes": 10,
      "difficulty": "beginner",
      "status": "published"
    }
  ],
  "total": 25,
  "page": 1,
  "limit": 10,
  "totalPages": 3,
  "hasNextPage": true,
  "hasPreviousPage": false
}
```

### Get Meditation by ID

Retrieve a specific meditation.

**Endpoint:** `GET /v1/meditations/:meditationId`

### Get Meditation by Slug

Retrieve a meditation by its slug.

**Endpoint:** `GET /v1/meditations/by-slug/:slug`

### Update Meditation

Update an existing meditation.

**Endpoint:** `PUT /v1/meditations/:meditationId` or
`PATCH /v1/meditations/:meditationId`

### Delete Meditation

Delete a meditation (soft delete by default).

**Endpoint:** `DELETE /v1/meditations/:meditationId`

**Query Parameters:**

| Parameter | Type    | Description                          |
| --------- | ------- | ------------------------------------ |
| `hard`    | boolean | Perform hard delete (default: false) |

**Response:** `204 No Content`

### Restore Meditation

Restore a soft-deleted meditation.

**Endpoint:** `POST /v1/meditations/:meditationId/restore`

---

## Filtering Endpoints

### Filter by Type

Get meditations by meditation type.

**Endpoint:** `GET /v1/meditations/by-type/:type`

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/meditations/by-type/breathing?limit=10" \
  -H "Authorization: Bearer <access_token>"
```

### Filter by Focus

Get meditations by focus area.

**Endpoint:** `GET /v1/meditations/by-focus/:focus`

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/meditations/by-focus/stress" \
  -H "Authorization: Bearer <access_token>"
```

### Filter by Difficulty

Get meditations by difficulty level.

**Endpoint:** `GET /v1/meditations/by-difficulty/:difficulty`

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/meditations/by-difficulty/beginner" \
  -H "Authorization: Bearer <access_token>"
```

### Filter by Duration

Get meditations within a duration range.

**Endpoint:** `GET /v1/meditations/by-duration`

**Query Parameters:**

| Parameter | Type    | Description                                |
| --------- | ------- | ------------------------------------------ |
| `min`     | integer | Minimum duration in minutes (default: 0)   |
| `max`     | integer | Maximum duration in minutes (default: 999) |

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/meditations/by-duration?min=5&max=15" \
  -H "Authorization: Bearer <access_token>"
```

### Filter by Instructor

Get meditations by instructor.

**Endpoint:** `GET /v1/meditations/by-instructor/:instructorId`

### Recommended for Time of Day

Get meditations recommended for a specific time.

**Endpoint:** `GET /v1/meditations/recommended/:time`

**Path Parameters:**

| Parameter | Values                                            |
| --------- | ------------------------------------------------- |
| `time`    | `morning`, `afternoon`, `evening`, `before_sleep` |

**Request:**

```bash
curl -X GET "https://api.lilith.app/v1/meditations/recommended/morning" \
  -H "Authorization: Bearer <access_token>"
```

### Search by Tags

Search meditations by tags.

**Endpoint:** `POST /v1/meditations/search/by-tags`

**Request Body:**

| Field      | Type     | Required | Description                       |
| ---------- | -------- | -------- | --------------------------------- |
| `tags`     | string[] | Yes      | Tags to search for                |
| `matchAll` | boolean  | No       | Require all tags (default: false) |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/meditations/search/by-tags" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "tags": ["morning", "beginner-friendly"],
    "matchAll": true
  }'
```

---

## Status Workflow

### Status Transition Diagram

```
┌─────────┐      ┌────────┐      ┌───────────┐
│  draft  │ ──→  │ review │ ──→  │ published │
└────┬────┘      └───┬────┘      └─────┬─────┘
     │               │                 │
     │               │                 ↓
     │               ↓           ┌──────────┐
     └─────────────→ deleted ←── │ archived │
                                 └──────────┘
```

### Transition Status

Manually transition meditation status.

**Endpoint:** `POST /v1/meditations/:meditationId/status`

**Request Body:**

| Field        | Type   | Required | Description              |
| ------------ | ------ | -------- | ------------------------ |
| `status`     | string | Yes      | Target status            |
| `reason`     | string | No       | Reason for transition    |
| `authorId`   | uuid   | No       | Author performing action |
| `authorName` | string | No       | Author name              |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/meditations/meditation_abc123/status" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "review",
    "reason": "Ready for editorial review"
  }'
```

### Publish Meditation

Quick publish action.

**Endpoint:** `POST /v1/meditations/:meditationId/publish`

### Archive Meditation

Archive a published meditation.

**Endpoint:** `POST /v1/meditations/:meditationId/archive`

### Get Allowed Transitions

Retrieve valid status transitions.

**Endpoint:** `GET /v1/meditations/:meditationId/allowed-transitions`

**Response:**

```json
{
  "currentStatus": "review",
  "allowedTransitions": ["draft", "published", "deleted"]
}
```

---

## Versioning

### List Versions

Retrieve all versions for a meditation.

**Endpoint:** `GET /v1/meditations/:meditationId/versions`

**Response:**

```json
{
  "versions": [
    {
      "id": "version_123",
      "contentType": "meditation",
      "contentId": "meditation_abc123",
      "versionNumber": 3,
      "contentSnapshot": { "title": "Current Title", "description": "..." },
      "changeSummary": "Updated audio quality",
      "authorName": "John Doe",
      "isCurrent": true,
      "createdAt": "2024-01-01T00:00:00.000Z"
    }
  ]
}
```

### Get Current Version

**Endpoint:** `GET /v1/meditations/:meditationId/versions/current`

### Get Specific Version

**Endpoint:** `GET /v1/meditations/:meditationId/versions/:versionNumber`

### Create Version

Create a new version snapshot.

**Endpoint:** `POST /v1/meditations/:meditationId/versions`

**Request Body:**

| Field           | Type   | Required | Description             |
| --------------- | ------ | -------- | ----------------------- |
| `changeSummary` | string | No       | Description of changes  |
| `authorId`      | uuid   | No       | Author creating version |
| `authorName`    | string | No       | Author name             |

### Restore Version

Restore a previous version.

**Endpoint:**
`POST /v1/meditations/:meditationId/versions/:versionNumber/restore`

---

## Localization

### Translation Status

| Status               | Description                  |
| -------------------- | ---------------------------- |
| `not_started`        | Translation not begun        |
| `in_progress`        | Translation in progress      |
| `machine_translated` | Machine translation complete |
| `human_reviewed`     | Human review complete        |
| `approved`           | Ready for publication        |

### List Locales

Retrieve all locales for a meditation.

**Endpoint:** `GET /v1/meditations/:meditationId/locales`

### Create Locale

Create a new locale translation.

**Endpoint:** `POST /v1/meditations/:meditationId/locales`

**Request Body:**

| Field           | Type    | Required | Description                       |
| --------------- | ------- | -------- | --------------------------------- |
| `locale`        | string  | Yes      | Locale code (e.g., `es`, `fr-CA`) |
| `isDefault`     | boolean | No       | Set as default locale             |
| `title`         | string  | No       | Translated title                  |
| `description`   | string  | No       | Translated description            |
| `introduction`  | string  | No       | Translated introduction           |
| `localizedData` | object  | No       | Additional localized fields       |
| `translatorId`  | uuid    | No       | Translator user ID                |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/meditations/meditation_abc123/locales" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "locale": "es",
    "title": "Conciencia de la Respiración Matutina",
    "description": "Comienza tu día con respiración consciente"
  }'
```

### Get Locale

**Endpoint:** `GET /v1/meditations/:meditationId/locales/:locale`

### Update Locale

**Endpoint:** `PUT /v1/meditations/:meditationId/locales/:locale`

### Delete Locale

**Endpoint:** `DELETE /v1/meditations/:meditationId/locales/:locale`

### Set Default Locale

**Endpoint:** `POST /v1/meditations/:meditationId/locales/:locale/set-default`

---

## Engagement Metrics

### Record Play

Increment play count.

**Endpoint:** `POST /v1/meditations/:meditationId/play`

**Response:**

```json
{ "success": true }
```

### Record Completion

Increment completion count.

**Endpoint:** `POST /v1/meditations/:meditationId/complete`

### Add Rating

Add a rating to a meditation.

**Endpoint:** `POST /v1/meditations/:meditationId/rate`

**Request Body:**

| Field    | Type   | Required | Description        |
| -------- | ------ | -------- | ------------------ |
| `rating` | number | Yes      | Rating value (0-5) |

**Request:**

```bash
curl -X POST "https://api.lilith.app/v1/meditations/meditation_abc123/rate" \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{ "rating": 4.5 }'
```

### Add to Favorites

Add meditation to user's favorites.

**Endpoint:** `POST /v1/meditations/:meditationId/favorite`

### Remove from Favorites

Remove meditation from user's favorites.

**Endpoint:** `DELETE /v1/meditations/:meditationId/favorite`

---

## Error Handling

### Error Codes

| Code                 | HTTP Status | Description                         |
| -------------------- | ----------- | ----------------------------------- |
| `NOT_FOUND`          | 404         | Meditation not found                |
| `INVALID_TRANSITION` | 400         | Invalid status transition           |
| `DUPLICATE`          | 409         | Meditation with slug already exists |
| `INVALID_VERSION`    | 400         | Version number must be an integer   |
| `INTERNAL_ERROR`     | 500         | Unexpected server error             |

### Example Error Response

```json
{
  "code": "INVALID_TRANSITION",
  "message": "Invalid status transition from 'draft' to 'archived'"
}
```

---

## SDK Integration

### TypeScript/JavaScript

```typescript
import { LilithClient } from '@lilith/sdk';

const client = new LilithClient({
  apiKey: process.env.LILITH_API_KEY,
});

// Create a meditation
const meditation = await client.content.createMeditation({
  slug: 'morning-breath-awareness',
  title: 'Morning Breath Awareness',
  type: 'breathing',
  focus: 'focus',
  durationMinutes: 10,
  difficulty: 'beginner',
});

// List meditations with filtering
const meditations = await client.content.listMeditations({
  type: 'breathing',
  difficulty: 'beginner',
  limit: 10,
});

// Get recommended for time of day
const morningMeditations =
  await client.content.getRecommendedMeditations('morning');

// Search by tags
const tagResults = await client.content.searchMeditationsByTags({
  tags: ['morning', 'short'],
  matchAll: true,
});

// Publish meditation
await client.content.publishMeditation('meditation_abc123');

// Create version
await client.content.createMeditationVersion('meditation_abc123', {
  changeSummary: 'Updated audio quality',
});

// Record engagement
await client.content.recordMeditationPlay('meditation_abc123');
await client.content.rateMeditation('meditation_abc123', { rating: 4.5 });
```

---

## Related Documentation

- [Lesson API](./lesson-api.md) - Course lesson management
- [Persona API](./persona-api.md) - AI persona management
- [Media API](./media-api.md) - Media asset management
- [Authentication](./authentication.md) - API authentication

---

## Questions?

- **Technical Support**: api-support@lilith.app
- **Documentation**: [GitHub Issues](https://github.com/lilith/platform/issues)
