# Integration Tests

This directory contains end-to-end integration tests for the Tara API.

## Prerequisites

Integration tests require a PostgreSQL database. The tests expect a test
database to be available.

### Database Setup

1. **Create the test database:**

   ```bash
   createdb tara_test
   ```

2. **Set the environment variable (optional):**

   ```bash
   export TEST_DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/tara_test
   ```

   If not set, the tests will default to:

   ```
   postgresql://oshun:oshun_dev@localhost:5432/tara_test
   ```

3. **Ensure the schema is created:** The test setup will attempt to use the
   existing schema. Make sure to run migrations on the test database if needed:
   ```bash
   # From the api directory
   DATABASE_URL=$TEST_DATABASE_URL pnpm run db:push
   ```

## Running Tests

### Run all integration tests:

```bash
pnpm run test:integration
```

### Run integration tests in watch mode:

```bash
pnpm run test:integration:watch
```

### Run specific test file:

```bash
pnpm run test:integration -- auth.integration.spec.ts
```

### Run all tests (unit + integration):

```bash
pnpm run test:all
```

## Test Structure

```
test/integration/
├── setup.ts                    # Database connection and cleanup utilities
├── fixtures.ts                 # Factory functions for creating test data
├── test-app.ts                 # Isolated test app instance with mock auth
├── auth.integration.spec.ts    # Authentication flow tests
├── content.integration.spec.ts # Content endpoint tests (meditations, courses)
├── progress.integration.spec.ts# Progress tracking tests
├── subscription.integration.spec.ts # Subscription flow tests
└── index.ts                    # Exports all utilities
```

## Test Utilities

### Setup Functions

- `initializeTestDatabase()` - Connect to test database
- `closeTestDatabase()` - Close database connection
- `cleanDatabase()` - Truncate all tables between tests
- `getTestDb()` - Get the Drizzle ORM instance

### Fixtures

- `createTestUser(overrides?)` - Create a test user
- `createTestMeditation(overrides?)` - Create a test meditation
- `createTestCourse(overrides?)` - Create a test course
- `createTestSubscription(userId, overrides?)` - Create a subscription
- `createTestSession(userId, meditationId, options?)` - Create a session

### Test App

- `createTestApp()` - Create an isolated Hono app for testing
- `createAuthenticatedRequest(app, token)` - Helper for authenticated requests

## Writing Tests

```typescript
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
import {
  initializeTestDatabase,
  closeTestDatabase,
  cleanDatabase,
} from './setup.js';
import { createTestUser, createTestMeditation } from './fixtures.js';
import { createTestApp } from './test-app.js';

describe('My Feature', () => {
  beforeAll(async () => {
    await initializeTestDatabase();
  });

  afterAll(async () => {
    await closeTestDatabase();
  });

  beforeEach(async () => {
    await cleanDatabase();
  });

  it('should work correctly', async () => {
    const app = createTestApp();
    const user = await createTestUser({ email: 'test@example.com' });

    // Test your feature
    const res = await app.request('/api/v1/some-endpoint', {
      headers: { Authorization: `Bearer ${accessToken}` },
    });

    expect(res.status).toBe(200);
  });
});
```

## Test Coverage

The integration tests cover:

### Authentication Flow

- User registration
- Login with credentials
- Token refresh
- Logout
- Protected route access
- Error handling

### Content Endpoints

- Meditation listing and filtering
- Single meditation retrieval
- Featured meditations
- Categories
- Courses and course meditations
- Collections

### Progress Tracking

- Streak information
- User statistics
- Session tracking
- Course progress
- Progress updates

### Subscription Flow

- Get current subscription
- Create checkout session
- Cancel subscription
- Restore subscription
- Subscription tiers and statuses
- Stripe integration fields

## CI/CD

For CI/CD pipelines, ensure:

1. A PostgreSQL service is available
2. The test database is created
3. The `TEST_DATABASE_URL` environment variable is set

Example GitHub Actions:

```yaml
services:
  postgres:
    image: postgres:16
    env:
      POSTGRES_USER: oshun
      POSTGRES_PASSWORD: oshun_dev
      POSTGRES_DB: tara_test
    ports:
      - 5432:5432

env:
  TEST_DATABASE_URL: postgresql://oshun:oshun_dev@localhost:5432/tara_test
```
