# Tara API Documentation

Comprehensive API documentation for the Tara Meditation App backend service.

## Overview

The Tara API is a RESTful service built with [Hono](https://hono.dev/)
framework, providing meditation content, user management, session tracking, and
progress analytics for the Tara meditation application ecosystem.

### Base URLs

| Environment | URL                            |
| ----------- | ------------------------------ |
| Production  | `https://api.tara.app`         |
| Staging     | `https://api.staging.tara.app` |
| Development | `http://localhost:3000`        |

### API Version

Current API version: **v1**

All endpoints are prefixed with `/api/v1/` unless otherwise noted.

## Quick Links

- [Authentication Guide](./authentication.md) - JWT tokens, OAuth, refresh flow
- [Endpoint Reference](./endpoints.md) - Complete API endpoint documentation
- [Error Handling](./errors.md) - Error codes and response formats
- [Rate Limiting](./rate-limiting.md) - Request limits and throttling

## Technology Stack

- **Framework**: Hono 4.0 with TypeScript
- **Validation**: Zod with OpenAPI/Swagger generation
- **Database**: PostgreSQL 16 with Drizzle ORM
- **Caching**: Redis for sessions and rate limiting
- **Authentication**: JWT with refresh token rotation

## Request Format

### Headers

All authenticated requests must include:

```http
Authorization: Bearer <access_token>
Content-Type: application/json
Accept: application/json
```

Optional headers:

```http
X-Request-ID: <uuid>           # Request correlation ID
X-Client-Version: <semver>     # Client app version
Accept-Language: en            # Preferred language (en, es, fr, de, ja, zh)
```

### Request Body

Request bodies must be valid JSON:

```json
{
  "field": "value",
  "nested": {
    "key": "value"
  }
}
```

## Response Format

### Success Response

All successful responses follow this structure:

```json
{
  "success": true,
  "data": {
    // Response payload
  },
  "meta": {
    "requestId": "550e8400-e29b-41d4-a716-446655440000",
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}
```

### Paginated Response

List endpoints return paginated responses:

```json
{
  "success": true,
  "data": {
    "items": [...],
    "pagination": {
      "page": 1,
      "limit": 20,
      "total": 150,
      "totalPages": 8,
      "hasNext": true,
      "hasPrev": false
    }
  },
  "meta": {
    "requestId": "550e8400-e29b-41d4-a716-446655440000",
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}
```

### Error Response

Error responses include detailed error information:

```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request parameters",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format"
      }
    ]
  },
  "meta": {
    "requestId": "550e8400-e29b-41d4-a716-446655440000",
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}
```

## Authentication Quick Start

### 1. Register a New User

```bash
curl -X POST https://api.tara.app/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePassword123!",
    "name": "John Doe"
  }'
```

### 2. Login

```bash
curl -X POST https://api.tara.app/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePassword123!"
  }'
```

Response:

```json
{
  "success": true,
  "data": {
    "accessToken": "eyJhbGciOiJIUzI1NiIs...",
    "refreshToken": "eyJhbGciOiJIUzI1NiIs...",
    "expiresIn": 900,
    "tokenType": "Bearer",
    "user": {
      "id": "usr_abc123",
      "email": "user@example.com",
      "name": "John Doe"
    }
  }
}
```

### 3. Make Authenticated Requests

```bash
curl -X GET https://api.tara.app/api/v1/users/me \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
```

### 4. Refresh Token

```bash
curl -X POST https://api.tara.app/api/v1/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{
    "refreshToken": "eyJhbGciOiJIUzI1NiIs..."
  }'
```

## API Endpoints Overview

### Health & Status

| Method | Endpoint   | Description             |
| ------ | ---------- | ----------------------- |
| GET    | `/health`  | Health check            |
| GET    | `/ready`   | Readiness check         |
| GET    | `/version` | API version information |

### Authentication

| Method | Endpoint                                | Description               |
| ------ | --------------------------------------- | ------------------------- |
| POST   | `/api/v1/auth/register`                 | Register new user         |
| POST   | `/api/v1/auth/login`                    | Login with credentials    |
| POST   | `/api/v1/auth/logout`                   | Logout and revoke tokens  |
| POST   | `/api/v1/auth/refresh`                  | Refresh access token      |
| POST   | `/api/v1/auth/forgot-password`          | Request password reset    |
| POST   | `/api/v1/auth/reset-password`           | Reset password with token |
| POST   | `/api/v1/auth/verify-email`             | Verify email address      |
| GET    | `/api/v1/auth/oauth/:provider`          | Initiate OAuth flow       |
| GET    | `/api/v1/auth/oauth/:provider/callback` | OAuth callback            |

### Users

| Method | Endpoint                       | Description              |
| ------ | ------------------------------ | ------------------------ |
| GET    | `/api/v1/users/me`             | Get current user profile |
| PATCH  | `/api/v1/users/me`             | Update profile           |
| DELETE | `/api/v1/users/me`             | Delete account           |
| GET    | `/api/v1/users/me/settings`    | Get user settings        |
| PUT    | `/api/v1/users/me/settings`    | Update settings          |
| GET    | `/api/v1/users/me/devices`     | List registered devices  |
| DELETE | `/api/v1/users/me/devices/:id` | Remove device            |

### Meditations

| Method | Endpoint                         | Description              |
| ------ | -------------------------------- | ------------------------ |
| GET    | `/api/v1/meditations`            | List meditations         |
| GET    | `/api/v1/meditations/:id`        | Get meditation details   |
| GET    | `/api/v1/meditations/:id/audio`  | Get audio stream URL     |
| GET    | `/api/v1/meditations/featured`   | Get featured meditations |
| GET    | `/api/v1/meditations/categories` | List categories          |
| GET    | `/api/v1/meditations/search`     | Search meditations       |

### Sessions

| Method | Endpoint                        | Description           |
| ------ | ------------------------------- | --------------------- |
| POST   | `/api/v1/sessions`              | Start new session     |
| GET    | `/api/v1/sessions`              | List user sessions    |
| GET    | `/api/v1/sessions/:id`          | Get session details   |
| PATCH  | `/api/v1/sessions/:id`          | Update session        |
| POST   | `/api/v1/sessions/:id/complete` | Mark session complete |

### Favorites

| Method | Endpoint                | Description           |
| ------ | ----------------------- | --------------------- |
| GET    | `/api/v1/favorites`     | List favorites        |
| POST   | `/api/v1/favorites`     | Add to favorites      |
| DELETE | `/api/v1/favorites/:id` | Remove from favorites |

### History

| Method | Endpoint              | Description            |
| ------ | --------------------- | ---------------------- |
| GET    | `/api/v1/history`     | Get meditation history |
| DELETE | `/api/v1/history`     | Clear history          |
| DELETE | `/api/v1/history/:id` | Remove history entry   |

### Progress

| Method | Endpoint                        | Description          |
| ------ | ------------------------------- | -------------------- |
| GET    | `/api/v1/progress/streak`       | Get current streak   |
| GET    | `/api/v1/progress/stats`        | Get statistics       |
| GET    | `/api/v1/progress/history`      | Get progress history |
| GET    | `/api/v1/progress/achievements` | Get achievements     |

### Subscriptions

| Method | Endpoint                        | Description             |
| ------ | ------------------------------- | ----------------------- |
| GET    | `/api/v1/subscriptions/status`  | Get subscription status |
| POST   | `/api/v1/subscriptions/verify`  | Verify receipt          |
| POST   | `/api/v1/subscriptions/restore` | Restore purchases       |

## SDK Support

### JavaScript/TypeScript

```typescript
import { TaraClient } from '@tara/sdk';

const tara = new TaraClient({
  baseUrl: 'https://api.tara.app',
  apiVersion: 'v1',
});

// Login
const { accessToken, user } = await tara.auth.login({
  email: 'user@example.com',
  password: 'password',
});

// Set token for subsequent requests
tara.setAccessToken(accessToken);

// Get meditations
const meditations = await tara.meditations.list({
  category: 'sleep',
  limit: 10,
});

// Start a session
const session = await tara.sessions.start({
  meditationId: 'med_123',
});
```

### React Native / Expo

```typescript
import { useTara } from '@tara/react-native';

function MeditationList() {
  const { meditations, isLoading } = useTara().useMeditations({
    category: 'focus',
  });

  if (isLoading) return <Loading />;

  return (
    <FlatList
      data={meditations}
      renderItem={({ item }) => <MeditationCard meditation={item} />}
    />
  );
}
```

## OpenAPI Specification

The API provides an OpenAPI 3.1 specification:

- **Swagger UI**: `https://api.tara.app/docs`
- **OpenAPI JSON**: `https://api.tara.app/openapi.json`
- **OpenAPI YAML**: `https://api.tara.app/openapi.yaml`

## Webhooks

Tara API supports webhooks for real-time event notifications:

### Supported Events

| Event                    | Description                  |
| ------------------------ | ---------------------------- |
| `user.created`           | New user registration        |
| `user.deleted`           | User account deleted         |
| `subscription.created`   | New subscription started     |
| `subscription.renewed`   | Subscription renewed         |
| `subscription.cancelled` | Subscription cancelled       |
| `subscription.expired`   | Subscription expired         |
| `session.completed`      | Meditation session completed |
| `streak.milestone`       | Streak milestone reached     |

### Webhook Payload

```json
{
  "id": "evt_abc123",
  "type": "session.completed",
  "created": "2024-01-15T10:30:00.000Z",
  "data": {
    "sessionId": "sess_xyz789",
    "userId": "usr_abc123",
    "meditationId": "med_456",
    "duration": 600
  }
}
```

### Webhook Security

Webhooks include a signature header for verification:

```http
X-Tara-Signature: sha256=5257a869e7c...
X-Tara-Timestamp: 1705315800
```

Verify the signature using HMAC-SHA256:

```typescript
import crypto from 'crypto';

function verifyWebhook(
  payload: string,
  signature: string,
  timestamp: string,
  secret: string
): boolean {
  const signedPayload = `${timestamp}.${payload}`;
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(signedPayload)
    .digest('hex');

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expectedSignature}`)
  );
}
```

## Support

- **Documentation**: https://docs.tara.app
- **API Status**: https://status.tara.app
- **Support Email**: api-support@tara.app
- **Developer Discord**: https://discord.gg/tara-dev

## Changelog

See [CHANGELOG.md](./CHANGELOG.md) for API version history and breaking changes.
