# TypeScript Types Reference

Complete TypeScript types and schemas reference for the Izri platform.

## 📋 Overview

All types are automatically generated from:

- Database schema (Drizzle ORM)
- tRPC router definitions
- Zod validation schemas

**Type Safety**:

- End-to-end type inference
- No manual type definitions needed
- Compile-time validation

---

## 🗄️ Database Types

### User

```typescript
type User = {
  id: string
  email: string
  name: string
  avatar?: string
  emailVerified: boolean
  createdAt: Date
  updatedAt: Date
}
```

**Source**: `users` table

**Relations**:

- `projects[]` - User's projects
- `organizationMembers[]` - Organization memberships
- `sessions[]` - Active sessions
- `accounts[]` - OAuth accounts (GitHub)

---

### Project

```typescript
type Project = {
  id: string
  name: string
  description?: string
  repository: string
  branch: string
  language: string
  framework?: string
  userId: string
  createdAt: Date
  updatedAt: Date
}
```

**Source**: `projects` table

**Relations**:

- `user` - Owner
- `settings` - Project settings
- `testRuns[]` - Test executions
- `projectAnalyses[]` - Repository analyses

---

### Organization

```typescript
type Organization = {
  id: string
  name: string
  slug: string
  description?: string
  createdAt: Date
  updatedAt: Date
}
```

**Source**: `organizations` table

**Relations**:

- `members[]` - Organization members
- `projects[]` - Organization projects (planned)

---

### OrganizationMember

```typescript
type OrganizationMember = {
  id: string
  organizationId: string
  userId: string
  role: 'OWNER' | 'ADMIN' | 'MEMBER' | 'VIEWER'
  createdAt: Date
}
```

**Source**: `organizationMembers` table

**Relations**:

- `organization` - Organization
- `user` - User

---

### ProjectSettings

```typescript
type ProjectSettings = {
  id: string
  projectId: string
  autoRunTests: boolean
  enableUnitTests: boolean
  enableIntegrationTests: boolean
  enableE2ETests: boolean
  notifyOnFailure: boolean
}
```

**Source**: `projectSettings` table

---

### TestRun

```typescript
type TestRun = {
  id: string
  projectId: string
  status: 'pending' | 'running' | 'completed' | 'failed'
  totalTests: number
  passedTests: number
  failedTests: number
  skippedTests: number
  duration?: number
  coverage?: number
  log?: string
  createdAt: Date
}
```

**Source**: `testRuns` table

---

### ProjectAnalysis

```typescript
type ProjectAnalysis = {
  id: string
  projectId: string
  repoUrl: string
  branch: string
  commitSha?: string
  analysis: AnalysisResult  // JSONB
  createdAt: Date
}
```

**Source**: `projectAnalyses` table

---

### Session

```typescript
type Session = {
  id: string
  userId: string
  expiresAt: Date
  createdAt: Date
  updatedAt: Date
  ipAddress?: string
  userAgent?: string
}
```

**Source**: `sessions` table (Better Auth)

---

### Account

```typescript
type Account = {
  id: string
  userId: string
  provider: 'github'
  providerAccountId: string
  accessToken?: string
  refreshToken?: string
  expiresAt?: Date
  createdAt: Date
}
```

**Source**: `accounts` table (Better Auth)

---

### ApiToken

```typescript
type ApiToken = {
  id: string
  userId: string
  name: string
  tokenHash: string
  scopes: string[]
  lastUsedAt?: Date
  expiresAt?: Date
  createdAt: Date
}
```

**Source**: `apiTokens` table

---

## 🔌 tRPC Types

### Router Input/Output Types

```typescript
import type { AppRouterInputs, AppRouterOutputs } from '@izri/trpc'

// Input types
type CreateProjectInput = AppRouterInputs['projects']['createProject']
type GetProjectInput = AppRouterInputs['projects']['getProject']
type UpdateProjectInput = AppRouterInputs['projects']['updateProject']

// Output types
type ProjectsOutput = AppRouterOutputs['projects']['getProjects']
type ProjectOutput = AppRouterOutputs['projects']['getProject']
type SessionOutput = AppRouterOutputs['auth']['getSession']
```

### Inferred Input Type Example

```typescript
type CreateProjectInput = {
  name: string
  repository: string
  userEmail: string
  description?: string
  branch?: string        // default: 'main'
  language?: string      // default: 'unknown'
  framework?: string
}
```

### Inferred Output Type Example

```typescript
type ProjectOutput = {
  project: {
    id: string
    name: string
    description?: string
    repository: string
    branch: string
    language: string
    framework?: string
    userId: string
    createdAt: Date
    updatedAt: Date
    testRuns: TestRun[]
    settings: ProjectSettings | null
  }
}
```

---

## ✅ Validation Schemas (Zod)

### Project Schema

```typescript
import { z } from 'zod'

const createProjectSchema = z.object({
  name: z.string().min(1),
  repository: z.string().min(1),
  userEmail: z.string().email(),
  description: z.string().optional(),
  branch: z.string().default('main'),
  language: z.string().optional(),
  framework: z.string().optional()
})

type CreateProjectInput = z.infer<typeof createProjectSchema>
```

### Organization Schema

```typescript
const createOrganizationSchema = z.object({
  name: z.string().min(1, 'Organization name is required'),
  slug: z
    .string()
    .min(1, 'Slug is required')
    .regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
  userEmail: z.string().email(),
  description: z.string().optional()
})
```

### Analysis Schema

```typescript
const analyzeRepositorySchema = z.object({
  projectId: z.string().ulid(),
  repoUrl: z.string().url(),
  userEmail: z.string().email(),
  branch: z.string().optional(),
  githubToken: z.string().optional(),
  options: z.object({
    maxFiles: z.number().optional(),
    maxFileSizeBytes: z.number().optional(),
    includeHashes: z.boolean().optional()
  }).optional()
})
```

---

## 📊 Analysis Types

### AnalysisResult

```typescript
type AnalysisResult = {
  files: FileAnalysis[]
  languages: Record<string, number>
  frameworks: string[]
  dependencies: Record<string, string>
  devDependencies?: Record<string, string>
  testFiles: string[]
  testCandidates: TestCandidate[]
  structure: StructureInfo
  commitSha: string
  analyzedAt: string
}
```

### FileAnalysis

```typescript
type FileAnalysis = {
  path: string
  language: string
  extension: string
  size: number
  hash?: string
  content?: string
  linesOfCode?: number
}
```

### TestCandidate

```typescript
type TestCandidate = {
  path: string
  priority: number
  reason: string
  suggestedTestPath?: string
}
```

### StructureInfo

```typescript
type StructureInfo = {
  directories: number
  files: number
  totalSize: number
  testCoverage?: number
}
```

---

## 🎯 Frontend Component Props

### ProjectCard Props

```typescript
type ProjectCardProps = {
  project: {
    id: string
    name: string
    description?: string
    repository: string
    language: string
    framework?: string
    testRuns: TestRun[]
  }
  onDelete?: (id: string) => void
}
```

### CreateProjectForm Props

```typescript
type CreateProjectFormProps = {
  onSuccess?: (project: Project) => void
  onCancel?: () => void
  defaultValues?: Partial<CreateProjectInput>
}
```

### AuthGuard Props

```typescript
type AuthGuardProps = {
  children: React.ReactNode
  fallback?: React.ReactNode
  redirectTo?: string
}
```

---

## 🔧 Utility Types

### Pagination

```typescript
type PaginationParams = {
  page?: number        // default: 1
  pageSize?: number    // default: 50
  orderBy?: string
  order?: 'asc' | 'desc'
}

type PaginationResult<T> = {
  items: T[]
  pagination: {
    total: number
    page: number
    pageSize: number
    totalPages: number
  }
}
```

### API Response

```typescript
type SuccessResponse<T> = {
  success: true
  data: T
  message?: string
}

type ErrorResponse = {
  success: false
  error: string
  message: string
  code?: string
}

type ApiResponse<T> = SuccessResponse<T> | ErrorResponse
```

---

## 🔐 Auth Context Types

### AuthContext

```typescript
type AuthContext = {
  user: User | null
  session: Session | null
  isAuthenticated: boolean
  isLoading: boolean
  signIn: (provider: 'github') => Promise<void>
  signOut: () => Promise<void>
  updateProfile: (data: Partial<User>) => Promise<void>
}
```

### UseAuth Hook Return

```typescript
type UseAuthReturn = {
  user: User | null
  session: Session | null
  isAuthenticated: boolean
  isLoading: boolean
}
```

---

## 🏢 Organization Types

### OrganizationWithRole

```typescript
type OrganizationWithRole = Organization & {
  role: 'OWNER' | 'ADMIN' | 'MEMBER' | 'VIEWER'
}
```

### MemberWithUser

```typescript
type MemberWithUser = {
  id: string
  userId: string
  email: string
  name: string
  role: 'OWNER' | 'ADMIN' | 'MEMBER' | 'VIEWER'
  createdAt: Date
}
```

---

## 🧪 Test Types (Planned)

### GeneratedTest

```typescript
type GeneratedTest = {
  id: string
  projectId: string
  filePath: string
  testCode: string
  language: string
  framework: string
  status: 'pending' | 'approved' | 'rejected'
  createdAt: Date
}
```

### TestResult

```typescript
type TestResult = {
  name: string
  status: 'passed' | 'failed' | 'skipped'
  duration: number
  error?: {
    message: string
    stack?: string
  }
}
```

---

## 🔗 Type Imports

### From Database Package

```typescript
import { 
  type User,
  type Project,
  type Organization,
  type Session,
  users,
  projects,
  organizations,
  sessions,
  db,
  eq,
  and,
  or,
  desc,
  asc
} from '@izri/database'
```

### From tRPC Package

```typescript
import { 
  type AppRouter, 
  type AppRouterInputs,
  type AppRouterOutputs
} from '@izri/trpc'

import { trpc } from '@/lib/trpc'
```

### From Auth Package

```typescript
import { 
  auth,
  authClient,
  type Session,
  type User
} from '@izri/auth'
```

### From Shared Package

```typescript
import {
  env,
  getEnvVar,
  type EnvConfig
} from '@izri/shared'
```

---

## 🎨 UI Component Types (shadcn/ui)

### Button

```typescript
type ButtonProps = {
  variant?: 'default' | 'destructive' | 'outline' | 'secondary' | 'ghost' | 'link'
  size?: 'default' | 'sm' | 'lg' | 'icon'
  asChild?: boolean
} & React.ButtonHTMLAttributes<HTMLButtonElement>
```

### Dialog

```typescript
type DialogProps = {
  open?: boolean
  onOpenChange?: (open: boolean) => void
  children: React.ReactNode
}
```

### Form

```typescript
type FormProps<T extends FieldValues> = {
  form: UseFormReturn<T>
  onSubmit: (data: T) => void | Promise<void>
  children: React.ReactNode
}
```

---

## 🔧 Generic Utility Types

### Nullable

```typescript
type Nullable<T> = T | null
```

### Optional

```typescript
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
```

### DeepPartial

```typescript
type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]
}
```

### Prettify

```typescript
type Prettify<T> = {
  [K in keyof T]: T[K]
} & {}
```

---

## 📝 Usage Examples

### Type-safe Database Query

```typescript
import { db, projects, eq } from '@izri/database'

const project = await db
  .select()
  .from(projects)
  .where(eq(projects.id, 'proj_123'))
  .limit(1)

// project is typed as Project[]
```

### Type-safe tRPC Call

```typescript
const { data } = await trpc.projects.getProjects.useQuery({
  userEmail: 'user@example.com'
})

// data is typed as { projects: Project[] }
```

### Type-safe Form

```typescript
import { useForm } from 'react-hook-form'
import type { AppRouterInputs } from '@izri/trpc'

type FormData = AppRouterInputs['projects']['createProject']

const form = useForm<FormData>({
  defaultValues: {
    name: '',
    repository: '',
    branch: 'main'
  }
})

const onSubmit = (data: FormData) => {
  // data is fully typed
  createProject(data)
}
```

---

## 🔗 Related Documentation

- [tRPC Routers](./trpc-routers.md) - API endpoint types
- [Database Package](../packages/database-package.md) - Schema definitions
- [tRPC Package](../packages/trpc-package.md) - Router definitions
- [Error Codes](./error-codes.md) - Error type definitions
