# Standardized API Route Pattern

This document describes the standardized pattern for API routes in the Harmonic SaaS codebase.

## Standard Pattern

All API routes should follow this structure:

```typescript
import { requireUserSession, requireSuperAdmin } from '../../utils/auth'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../utils/errors'
import { validateBody } from '../../utils/bodyValidation'
import { z } from 'zod'

// Define request/response interfaces
interface MyRequest {
  // Request fields
}

interface MyResponse {
  // Response fields
}

// Optional: Define Zod schema for validation
const schema = z.object({
  // Validation rules
})

export default defineEventHandler(async (event) => {
  try {
    // 1. Authentication & Authorization
    const session = await requireUserSession(event)
    // OR for super-admin routes:
    // await requireSuperAdmin(event)

    // 2. Method validation (if needed)
    assertMethod(event, 'POST') // or 'GET', 'PUT', 'DELETE', etc.

    // 3. Request body validation
    const body = await validateBody(event, schema) // OR readBody(event) for manual validation
    
    // 4. Business logic validation
    if (!body.requiredField) {
      throw ApiErrors.validationError('Required field is missing')
    }

    // 5. Business logic
    const result = await processRequest(session, body)

    // 6. Return standardized success response
    return createSuccessResponse<MyResponse>(result, 'Operation successful')
  } catch (error) {
    // 7. Handle errors consistently
    throw handleApiError(error)
  }
})
```

## Key Components

### 1. Error Handling

**Always use `handleApiError()` in catch blocks:**

```typescript
try {
  // ... logic
} catch (error) {
  throw handleApiError(error)
}
```

**Use `ApiErrors` helpers for common errors:**

```typescript
throw ApiErrors.validationError('Field is required')
throw ApiErrors.notFound('Resource not found')
throw ApiErrors.forbidden('Access denied')
throw ApiErrors.unauthorized('Not authenticated')
throw ApiErrors.badRequest('Invalid request')
```

### 2. Success Responses

**Always use `createSuccessResponse()`:**

```typescript
return createSuccessResponse<ResponseType>(data, 'Optional success message')
```

This ensures consistent `ApiResponse<T>` format:
```typescript
{
  success: true,
  data: T,
  message?: string
}
```

### 3. Authentication

**For regular user routes:**
```typescript
const session = await requireUserSession(event)
```

**For super-admin routes:**
```typescript
await requireSuperAdmin(event)
// This automatically checks for super admin access
```

**Don't manually check `user.superAdmin`** - use `requireSuperAdmin()` instead.

### 4. Request Validation

**Use Zod schemas with `validateBody()`:**
```typescript
const schema = z.object({
  email: z.string().email(),
  name: z.string().min(1)
})

const body = await validateBody(event, schema)
```

**Or manually validate and throw `ApiErrors.validationError()`:**
```typescript
const body = await readBody(event)
if (!body.email) {
  throw ApiErrors.validationError('Email is required')
}
```

## Examples

### Simple GET Route

```typescript
import { requireUserSession } from '../../utils/auth'
import { handleApiError, createSuccessResponse } from '../../utils/errors'

export default defineEventHandler(async (event) => {
  try {
    const session = await requireUserSession(event)
    const data = await fetchUserData(session.user.id)
    return createSuccessResponse(data)
  } catch (error) {
    throw handleApiError(error)
  }
})
```

### POST Route with Validation

```typescript
import { requireUserSession } from '../../utils/auth'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../utils/errors'
import { validateBody } from '../../utils/bodyValidation'
import { z } from 'zod'

const schema = z.object({
  name: z.string().min(1),
  email: z.string().email()
})

export default defineEventHandler(async (event) => {
  try {
    assertMethod(event, 'POST')
    const session = await requireUserSession(event)
    const body = await validateBody(event, schema)
    
    const result = await updateUser(session.user.id, body)
    return createSuccessResponse(result, 'User updated successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
```

### Super-Admin Route

```typescript
import { requireSuperAdmin } from '../../utils/auth'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../utils/errors'

export default defineEventHandler(async (event) => {
  try {
    await requireSuperAdmin(event)
    const body = await readBody(event)
    
    if (!body.userId) {
      throw ApiErrors.validationError('User ID is required')
    }
    
    const result = await adminAction(body.userId)
    return createSuccessResponse(result)
  } catch (error) {
    throw handleApiError(error)
  }
})
```

## Benefits

1. **Consistent Error Handling**: All errors follow the same format
2. **Type Safety**: Proper TypeScript types for requests/responses
3. **Better Debugging**: Structured error responses with codes
4. **Maintainability**: Easy to understand and modify
5. **Client Compatibility**: Works seamlessly with `useApiClient()` and `ApiResponse<T>`

## Migration Checklist

When updating existing routes:

- [ ] Wrap logic in try/catch
- [ ] Replace `createError()` with `ApiErrors.*` helpers
- [ ] Replace manual `{ success: true, ... }` with `createSuccessResponse()`
- [ ] Replace manual `user.superAdmin` checks with `requireSuperAdmin()`
- [ ] Add proper TypeScript interfaces for request/response
- [ ] Use `handleApiError()` in catch block

