# Test Database Setup

This directory contains the test database setup and utilities for running tests against a Supabase local database using Vitest.

## Overview

The test database is automatically set up before all tests run (via Vitest global setup) and torn down after all tests complete. It creates 3 test users with related data across all main database tables.

## Prerequisites

Before running tests, ensure:

1. **Supabase local is running**: `supabase start` (or configure `.env.test` to point to a test instance)
2. **Environment variables are set** in `.env.test`:
   ```bash
   SUPABASE_URL=http://localhost:54321  # Your local Supabase URL
   SUPABASE_SERVICE_ROLE_KEY=your-service-role-key-here
   SUPABASE_CONNECTION_STRING=postgresql://...
   # ... other required env vars
   ```

## Test Data

### Test Users

- **test_owner@example.com**: Main owner with full permissions
- **test_collab@example.com**: Collaborator with access to shared tablos
- **test_temp@example.com**: Temporary user (is_temporary=true)

All test users have the password: `test_password_123`, `test_password_456`, `test_password_789` respectively.

### Tables Populated

The setup creates test data in the following tables:
- `auth.users` (via Supabase admin API)
- `profiles` 
- `tablos`
- `tablo_access`
- `events`
- `event_types`
- `notes`
- `note_access`
- `shared_notes`
- `availabilities`
- `user_introductions`
- `feedbacks`
- `tablo_invites`

All string IDs are prefixed with `test_` for easy identification and cleanup.

## Using Test Data in Tests

### Import Test Utilities

```typescript
import { getTestUser, getAuthHeader } from "../helpers/testUtils.js";
```

### Get Test User Data

```typescript
const ownerUser = getTestUser("owner");
const collabUser = getTestUser("collab");
const tempUser = getTestUser("temp");
```

### Make Authenticated Requests

```typescript
const res = await client.someEndpoint.$get({
  headers: getAuthHeader("owner"),
});
```

### Example Test

```typescript
it("should work with authenticated user", async () => {
  const testUtils = await import("../helpers/testUtils.js");
  const { getAuthHeader, getTestUser } = testUtils;

  const app = new Hono();
  app.use(middlewareManager.supabase);
  app.use(middlewareManager.auth);
  app.get("/test", (c) => {
    const user = c.get("user");
    return c.json({ userId: user?.id });
  });

  const client = testClient(app);
  const testUser = getTestUser("owner");
  
  const res = await client.test.$get({
    headers: getAuthHeader("owner"),
  });
  
  const data = await res.json();
  assert.strictEqual(data.userId, testUser.userId);
});
```

## Running Tests

```bash
# Run all tests once
npm test

# Run tests in watch mode (re-runs on file changes)
npm run test:watch

# Run tests with UI (visual test runner)
npm run test:ui
```

## How It Works

1. **Vitest Global Setup** (`globalSetup.ts`) runs once before all tests
   - Calls `setupTestDatabase()` to create test users and data
2. Test data is inserted into all tables in the correct dependency order
3. Access tokens are generated for each user and stored
4. All test files can import and use `testUtils` to get user data and auth headers
5. **Vitest Global Teardown** runs once after all tests complete
   - Calls `teardownTestDatabase()` to clean up all test data

## Files

- **Config & Setup:**
  - `vitest.config.ts` (root): Vitest configuration
  - `globalSetup.ts`: Vitest global setup/teardown hooks
  - `setup.ts`: Per-test-file setup (currently minimal)

- **Test Data & Utilities:**
  - `fixtures/testData.ts`: Test data definitions
  - `helpers/dbSetup.ts`: Database setup and teardown functions
  - `helpers/testUtils.ts`: Helper functions for accessing test data in tests

- **Test Files:**
  - `auth/*.test.ts`: Authentication router tests
  - `helpers/*.test.ts`: Helper function tests
  - `middlewares/*.test.ts`: Middleware tests
  - `routes/*.test.ts`: API route tests

## Migration from Node Test Runner

The project has been migrated from Node.js built-in test runner to Vitest:

- **Before:** `import assert from "node:assert/strict"; import { describe, it } from "node:test";`
- **After:** `import { describe, it, expect } from "vitest";`
- **Assertions:** `assert.strictEqual(a, b)` → `expect(a).toBe(b)`
- **Global Setup:** Now uses Vitest's `globalSetup` instead of a test file that runs alphabetically

## Notes

- The test database must be running (Supabase local)
- Environment variables must be set in `.env.test`
- Console statements in setup/teardown are intentional for debugging
- All test data is prefixed with `test_` for easy cleanup
- Tests run in a single fork for consistency (`singleFork: true` in config)

