# API Reference

> Complete API documentation for all endpoints

## 📋 Overview

This section provides comprehensive API documentation for Izri, covering all tRPC procedures, REST endpoints, and webhook integrations. This reference is essential for frontend developers and API consumers.

## 🎯 API Architecture

- **Primary API**: tRPC for type-safe communication
- **REST Fallback**: Limited REST endpoints for non-TypeScript clients
- **Webhooks**: GitHub webhook integration for automation

## 📚 Documentation Pages

### [tRPC Procedures](./trpc-procedures.md)

**Complete tRPC API reference**

- All query procedures
- All mutation procedures
- Input/output types
- Error handling
- Usage examples
- Authentication requirements

### [REST Endpoints](./rest-endpoints.md)

**HTTP REST API reference**

- Available endpoints
- Request/response formats
- Authentication headers
- Error codes
- Rate limiting
- Examples with curl

### [Webhooks](./webhooks.md)

**Webhook integration guide**

- GitHub webhooks
- Event types
- Payload formats
- Signature verification
- Handler implementation
- Testing webhooks

## 🚀 API Overview

### Base URLs

| Environment | URL |
|-------------|-----|
| Development | `http://localhost:4000` |
| Production | `https://api.izri.com` |

### Authentication

```typescript
// Session-based (current)
// Cookie sent automatically by browser

// API Token (future)
headers: {
  'Authorization': 'Bearer your-api-token'
}
```

## 📡 tRPC Procedures

### Queries (Read Operations)

| Procedure | Input | Output | Description |
|-----------|-------|--------|-------------|
| `health` | - | `{ ok: boolean }` | Health check (tRPC query) |
| `auth.getSession` | - | `SessionInfo` | Get current session |
| `auth.getProfile` | - | `User` | Get user profile |
| `auth.listSessions` | - | `Session[]` | List user sessions |
| `auth.getAuditLogs` | `{ limit, offset }` | `AuditLog[]` | Get auth audit logs |
| `projects.getProjects` | `{ userEmail }` | `Project[]` | Get user's projects |
| `projects.getProject` | `{ projectId, userEmail }` | `Project` | Get single project |
| `projects.getProjectAnalyses` | `{ projectId, userEmail }` | `Analysis[]` | Get project analyses |
| `projects.getLatestProjectAnalysis` | `{ projectId, userEmail }` | `Analysis` | Get latest analysis |
| `organizations.list` | `{ userEmail }` | `Organization[]` | List user's organizations |
| `organizations.getBySlug` | `{ slug, userEmail }` | `Organization` | Get organization by slug |
| `organizations.getMembers` | `{ organizationId, userEmail }` | `Member[]` | Get organization members |
| `github.getGitHubRepositories` | `{ userEmail }` | `Repository[]` | Get GitHub repos |

### Mutations (Write Operations)

| Procedure | Input | Output | Description |
|-----------|-------|--------|-------------|
| `auth.invalidateSession` | - | `{ success: boolean }` | Logout current session |
| `auth.revokeSession` | `{ sessionToken }` | `{ success: boolean }` | Revoke specific session |
| `auth.revokeOtherSessions` | - | `{ success: boolean }` | Revoke all other sessions |
| `auth.updateProfile` | `{ name?, avatar? }` | `User` | Update user profile |
| `projects.createProject` | `CreateProjectInput` | `Project` | Create new project |
| `projects.updateProject` | `UpdateProjectInput` | `Project` | Update project |
| `projects.deleteProject` | `{ projectId, userEmail }` | `{ message }` | Delete project |
| `projects.updateProjectSettings` | `{ projectId, userEmail, settings }` | `ProjectSettings` | Update project settings |
| `organizations.create` | `{ name, slug, userEmail, description? }` | `Organization` | Create organization |
| `organizations.update` | `{ organizationId, userEmail, ... }` | `Organization` | Update organization |
| `organizations.delete` | `{ organizationId, userEmail }` | `{ message }` | Delete organization |
| `organizations.inviteMember` | `{ organizationId, userEmail, userToInviteEmail, role }` | `Member` | Invite user to organization |
| `organizations.updateMemberRole` | `{ organizationId, membershipId, userEmail, role }` | `Member` | Update member role |
| `organizations.removeMember` | `{ organizationId, membershipId, userEmail }` | `{ message }` | Remove organization member |
| `analysis.analyzeRepository` | `{ projectId, repoUrl, userEmail, ... }` | `AnalysisResult` | Analyze repository |

## 📝 Common Types

### Project

```typescript
interface Project {
  id: string
  name: string
  description: string | null
  repository: string
  branch: string
  language: string
  framework: string | null
  userId: string
  organizationId: string | null
  createdAt: Date
  updatedAt: Date
  testRuns?: TestRun[]
}
```

### TestRun

```typescript
interface TestRun {
  id: string
  projectId: string
  userId: string
  status: TestStatus
  type: TestType
  totalTests: number
  passedTests: number
  failedTests: number
  skippedTests: number
  coverage: number | null
  duration: number | null
  startedAt: Date | null
  completedAt: Date | null
  createdAt: Date
}

enum TestStatus {
  PENDING = 'PENDING',
  RUNNING = 'RUNNING',
  COMPLETED = 'COMPLETED',
  FAILED = 'FAILED',
  CANCELLED = 'CANCELLED'
}

enum TestType {
  UNIT = 'UNIT',
  INTEGRATION = 'INTEGRATION',
  E2E = 'E2E',
  ALL = 'ALL'
}
```

### Repository

```typescript
interface Repository {
  id: number
  name: string
  fullName: string
  description: string | null
  url: string
  cloneUrl: string
  language: string
  stars: number
  forks: number
  isPrivate: boolean
  updatedAt: string
  defaultBranch: string
}
```

## 🔧 Usage Examples

### TypeScript/JavaScript (tRPC Client)

```typescript
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client'
import type { AppRouter } from '@izri/trpc'

const client = createTRPCProxyClient<AppRouter>({
  links: [
    httpBatchLink({
      url: 'http://localhost:4000/trpc',
    }),
  ],
})

// Query
const projects = await client.getProjects.query({
  userEmail: 'user@example.com'
})

// Mutation
const newProject = await client.createProject.mutate({
  name: 'My Project',
  description: 'A test project',
  repository: 'https://github.com/user/repo',
  branch: 'main',
  language: 'typescript',
  userEmail: 'user@example.com'
})
```

### React (tRPC Hooks)

```tsx
import { trpc } from '~/lib/trpc'

function MyComponent() {
  // Query with auto-refetch
  const { data, isLoading, error } = trpc.getProjects.useQuery({
    userEmail: 'user@example.com'
  })

  // Mutation with optimistic updates
  const createProject = trpc.createProject.useMutation({
    onSuccess: () => {
      // Invalidate and refetch
      trpc.useContext().getProjects.invalidate()
    }
  })

  const handleCreate = () => {
    createProject.mutate({
      name: 'New Project',
      repository: 'https://github.com/user/repo',
      branch: 'main',
      language: 'typescript',
      userEmail: 'user@example.com'
    })
  }

  if (isLoading) return <div>Loading...</div>
  if (error) return <div>Error: {error.message}</div>

  return (
    <div>
      {data?.map(project => (
        <div key={project.id}>{project.name}</div>
      ))}
      <button onClick={handleCreate}>Create Project</button>
    </div>
  )
}
```

### curl (REST)

```bash
# Health check
curl http://localhost:4000/health

# tRPC query (POST with JSON body)
curl -X POST http://localhost:4000/trpc/getProjects \
  -H "Content-Type: application/json" \
  -d '{"userEmail":"user@example.com"}'

# tRPC mutation
curl -X POST http://localhost:4000/trpc/createProject \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My Project",
    "repository": "https://github.com/user/repo",
    "branch": "main",
    "language": "typescript",
    "userEmail": "user@example.com"
  }'
```

## ⚠️ Error Handling

### Error Response Format

```typescript
interface TRPCError {
  message: string
  code: string
  data?: {
    code: string
    httpStatus: number
    path: string
    stack?: string
  }
}
```

### Error Codes

| Code | HTTP Status | Description |
|------|-------------|-------------|
| `BAD_REQUEST` | 400 | Invalid input |
| `UNAUTHORIZED` | 401 | Authentication required |
| `FORBIDDEN` | 403 | Permission denied |
| `NOT_FOUND` | 404 | Resource not found |
| `INTERNAL_SERVER_ERROR` | 500 | Server error |
| `TIMEOUT` | 504 | Request timeout |

### Error Handling Example

```typescript
try {
  const project = await client.getProject.query({ id: 'invalid-id' })
} catch (error) {
  if (error instanceof TRPCClientError) {
    if (error.data?.code === 'NOT_FOUND') {
      console.log('Project not found')
    } else {
      console.error('API error:', error.message)
    }
  }
}
```

## 📊 Rate Limiting

### Planned Limits (Not Yet Implemented)

Rate limiting is planned for future implementation to protect against abuse and ensure fair usage.

| Endpoint Type | Planned Rate Limit | Window |
|---------------|-------------------|--------|
| Read (queries) | 100 requests | 1 minute |
| Write (mutations) | 20 requests | 1 minute |
| Webhooks | 10 requests | 1 minute |

### Future Rate Limit Headers

Once implemented, these headers will be included in responses:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640000000
Retry-After: 60
```

## 🔐 Authentication

### Session Authentication (Current)

```typescript
// Automatically handled by browser cookies
// No additional headers required
```

### API Token Authentication (Planned)

```typescript
// In headers
{
  'Authorization': 'Bearer your-api-token'
}

// Example
fetch('http://localhost:4000/trpc/getProjects', {
  headers: {
    'Authorization': 'Bearer sk_live_...'
  }
})
```

## 🔗 Related Documentation

- **Backend**: [Backend Documentation](../backend/README.md)
- **Frontend**: [tRPC Integration](../frontend/trpc-integration.md)
- **Packages**: [tRPC Package](../packages/trpc.md)

## 📖 Additional Resources

- [tRPC Documentation](https://trpc.io)
- [Hono Documentation](https://hono.dev)
- [Drizzle ORM](https://orm.drizzle.team)

---

*Explore detailed API documentation →*

- [tRPC Procedures Reference](./trpc-procedures.md)
- [REST Endpoints Reference](./rest-endpoints.md)
- [Webhooks Integration](./webhooks.md)
