# Yemaya Code Style Guide

This guide defines the coding standards and best practices for the Yemaya
project. Following these guidelines ensures consistency across the codebase and
makes code reviews more efficient.

## Table of Contents

- [General Principles](#general-principles)
- [TypeScript Guidelines](#typescript-guidelines)
- [React Guidelines](#react-guidelines)
- [API Guidelines](#api-guidelines)
- [Database Guidelines](#database-guidelines)
- [Testing Guidelines](#testing-guidelines)
- [Git Workflow](#git-workflow)

---

## General Principles

### Clarity Over Cleverness

Write code that is easy to understand. Future maintainers (including yourself)
will thank you.

```typescript
// Bad - clever but unclear
const r = a.reduce((p, c) => (c.s ? [...p, c] : p), []);

// Good - clear and readable
const activeItems = items.filter((item) => item.isActive);
```

### Single Responsibility

Functions and classes should do one thing well.

```typescript
// Bad - function does too much
async function processUser(userId: string) {
  const user = await db.user.findUnique({ where: { id: userId } });
  const orders = await db.order.findMany({ where: { userId } });
  await sendEmail(user.email, formatOrderSummary(orders));
  await updateLastActivity(userId);
  return { user, orders };
}

// Good - separated concerns
async function getUser(userId: string) {
  return db.user.findUnique({ where: { id: userId } });
}

async function getUserOrders(userId: string) {
  return db.order.findMany({ where: { userId } });
}

async function sendOrderSummary(user: User, orders: Order[]) {
  const summary = formatOrderSummary(orders);
  await sendEmail(user.email, summary);
}
```

### Explicit Over Implicit

Be explicit about types, return values, and error handling.

```typescript
// Bad - implicit
function process(data) {
  return data.map((x) => x.value);
}

// Good - explicit
function extractValues(items: Item[]): number[] {
  return items.map((item) => item.value);
}
```

### Fail Fast

Validate inputs early and fail with clear error messages.

```typescript
// Good - validate early
function createProject(input: CreateProjectInput): Project {
  if (!input.name || input.name.length === 0) {
    throw new ValidationError('Project name is required');
  }
  if (input.name.length > 100) {
    throw new ValidationError('Project name must be 100 characters or less');
  }
  // ... proceed with creation
}
```

---

## TypeScript Guidelines

### Use Strict Mode

All packages use strict TypeScript:

```json
{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true
  }
}
```

### Type Definitions

#### Prefer Interfaces for Object Shapes

```typescript
// Good
interface User {
  id: string;
  name: string;
  email: string;
}

// Use type for unions, intersections, and mapped types
type UserRole = 'admin' | 'editor' | 'viewer';
type UserWithRole = User & { role: UserRole };
```

#### Avoid `any`

Use `unknown` when type is truly unknown, then narrow with type guards.

```typescript
// Bad
function processData(data: any) {
  return data.value;
}

// Good
function processData(data: unknown): number {
  if (isValidData(data)) {
    return data.value;
  }
  throw new Error('Invalid data format');
}

function isValidData(data: unknown): data is { value: number } {
  return (
    typeof data === 'object' &&
    data !== null &&
    'value' in data &&
    typeof (data as any).value === 'number'
  );
}
```

#### Use Generics Appropriately

```typescript
// Good - generic provides type safety
function first<T>(items: T[]): T | undefined {
  return items[0];
}

// Usage is type-safe
const user = first(users); // type: User | undefined
const name = first(names); // type: string | undefined
```

### Null Handling

#### Use Optional Chaining and Nullish Coalescing

```typescript
// Good
const userName = user?.profile?.name ?? 'Anonymous';

// Avoid
const userName =
  user && user.profile && user.profile.name ? user.profile.name : 'Anonymous';
```

#### Be Explicit About Nullable Types

```typescript
// Good - explicitly nullable
interface UserQuery {
  id: string;
  includeDeleted?: boolean; // optional
}

function findUser(id: string): User | null {
  // explicitly returns null if not found
}
```

### Enums and Constants

#### Prefer const objects over enums

```typescript
// Preferred
export const ProjectStatus = {
  DRAFT: 'draft',
  ACTIVE: 'active',
  ARCHIVED: 'archived',
} as const;

export type ProjectStatus = (typeof ProjectStatus)[keyof typeof ProjectStatus];

// Usage
const status: ProjectStatus = ProjectStatus.ACTIVE;
```

#### Use UPPER_SNAKE_CASE for constants

```typescript
const MAX_RETRIES = 3;
const DEFAULT_PAGE_SIZE = 20;
const API_BASE_URL = 'https://api.yemaya.io';
```

### Imports

#### Order imports consistently

```typescript
// 1. Node built-ins
import { readFile } from 'fs/promises';
import path from 'path';

// 2. External packages
import { z } from 'zod';
import { Hono } from 'hono';

// 3. Internal packages (@yemaya/*)
import { db } from '@yemaya/database';
import { ApiError } from '@yemaya/core';

// 4. Relative imports
import { UserService } from './user-service';
import { validateEmail } from '../utils';

// 5. Type imports (separate if needed)
import type { User, Project } from '@yemaya/types';
```

#### Use path aliases

```typescript
// Good - using aliases
import { Button } from '@/components/Button';
import { useAuth } from '@/hooks/useAuth';

// Avoid - deep relative paths
import { Button } from '../../../../components/Button';
```

### Function Patterns

#### Use async/await over raw promises

```typescript
// Good
async function fetchUser(id: string): Promise<User> {
  const response = await fetch(`/api/users/${id}`);
  if (!response.ok) {
    throw new ApiError('USER_FETCH_FAILED', 'Failed to fetch user');
  }
  return response.json();
}

// Avoid
function fetchUser(id: string): Promise<User> {
  return fetch(`/api/users/${id}`).then((response) => {
    if (!response.ok) {
      throw new ApiError('USER_FETCH_FAILED', 'Failed to fetch user');
    }
    return response.json();
  });
}
```

#### Use arrow functions for callbacks

```typescript
// Good
const activeUsers = users.filter((user) => user.isActive);
const names = users.map((user) => user.name);

// Use function declarations for top-level functions
export function processUsers(users: User[]): ProcessedUser[] {
  return users.map(transformUser);
}
```

---

## React Guidelines

### Component Structure

```typescript
// components/UserCard/UserCard.tsx

// 1. Imports
import { type ComponentProps } from 'react';
import { cn } from '@/utils/cn';

// 2. Types
interface UserCardProps {
  user: User;
  variant?: 'compact' | 'full';
  onSelect?: (user: User) => void;
}

// 3. Component
export function UserCard({
  user,
  variant = 'full',
  onSelect,
}: UserCardProps) {
  // 3a. Hooks
  const { isAdmin } = useAuth();
  const [isExpanded, setIsExpanded] = useState(false);

  // 3b. Derived state
  const displayName = user.name || user.email;

  // 3c. Event handlers
  const handleClick = useCallback(() => {
    onSelect?.(user);
  }, [user, onSelect]);

  // 3d. Effects
  useEffect(() => {
    // ...
  }, []);

  // 3e. Early returns for loading/error states
  if (!user) {
    return null;
  }

  // 3f. Render
  return (
    <div className={cn('user-card', variants[variant])}>
      {/* ... */}
    </div>
  );
}

// 4. Display name (for debugging)
UserCard.displayName = 'UserCard';
```

### Hooks

#### Custom hooks start with `use`

```typescript
// hooks/useProjects.ts
export function useProjects(options?: UseProjectsOptions) {
  const query = useQuery({
    queryKey: ['projects', options],
    queryFn: () => fetchProjects(options),
  });

  return {
    projects: query.data ?? [],
    isLoading: query.isLoading,
    error: query.error,
    refetch: query.refetch,
  };
}
```

#### Extract complex logic into hooks

```typescript
// Bad - too much logic in component
function ProjectList() {
  const [projects, setProjects] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [page, setPage] = useState(1);
  // ... 50 more lines of data fetching logic

  return <div>...</div>;
}

// Good - logic extracted to hook
function ProjectList() {
  const { projects, isLoading, error, loadMore } = useProjects();

  if (isLoading) return <Skeleton />;
  if (error) return <ErrorMessage error={error} />;

  return (
    <div>
      {projects.map(project => (
        <ProjectCard key={project.id} project={project} />
      ))}
      <Button onClick={loadMore}>Load More</Button>
    </div>
  );
}
```

### State Management

#### Use appropriate state solution

| Scope                   | Solution        |
| ----------------------- | --------------- |
| Component local         | `useState`      |
| Shared between siblings | Lift state up   |
| Global client state     | Zustand         |
| Server state            | TanStack Query  |
| Form state              | React Hook Form |
| URL state               | React Router    |

#### Avoid prop drilling

```typescript
// Bad - drilling through many levels
<App user={user}>
  <Layout user={user}>
    <Sidebar user={user}>
      <UserMenu user={user} />
    </Sidebar>
  </Layout>
</App>

// Good - use context or store
<AuthProvider>
  <App>
    <Layout>
      <Sidebar>
        <UserMenu /> {/* gets user from useAuth() */}
      </Sidebar>
    </Layout>
  </App>
</AuthProvider>
```

### Styling

#### Use Tailwind CSS with cn utility

```typescript
import { cn } from '@/utils/cn';

function Button({ variant, size, className, ...props }) {
  return (
    <button
      className={cn(
        // Base styles
        'inline-flex items-center justify-center rounded-md font-medium',
        'focus-visible:outline-none focus-visible:ring-2',
        'disabled:pointer-events-none disabled:opacity-50',
        // Variant styles
        {
          'bg-primary text-primary-foreground hover:bg-primary/90':
            variant === 'primary',
          'bg-secondary text-secondary-foreground hover:bg-secondary/80':
            variant === 'secondary',
        },
        // Size styles
        {
          'h-8 px-3 text-sm': size === 'sm',
          'h-10 px-4': size === 'md',
          'h-12 px-6 text-lg': size === 'lg',
        },
        // Custom className
        className
      )}
      {...props}
    />
  );
}
```

#### Use CSS variables for theming

```css
:root {
  --color-primary: 220 90% 56%;
  --color-background: 0 0% 100%;
  --color-foreground: 222 47% 11%;
}

.dark {
  --color-primary: 217 91% 60%;
  --color-background: 222 47% 11%;
  --color-foreground: 210 40% 98%;
}
```

---

## API Guidelines

### Route Design

#### Use resource-based URLs

```typescript
// Good
GET    /projects              // List projects
POST   /projects              // Create project
GET    /projects/:id          // Get project
PATCH  /projects/:id          // Update project
DELETE /projects/:id          // Delete project
GET    /projects/:id/members  // List project members

// Avoid
GET    /getProjects
POST   /createProject
GET    /getProjectById/:id
```

#### Use appropriate HTTP methods

| Method | Use                       |
| ------ | ------------------------- |
| GET    | Retrieve resources        |
| POST   | Create resources, actions |
| PATCH  | Partial updates           |
| PUT    | Full replacement          |
| DELETE | Remove resources          |

### Request/Response

#### Use Zod schemas

```typescript
import { z } from '@hono/zod-openapi';

const CreateProjectSchema = z.object({
  name: z
    .string()
    .min(1, 'Name is required')
    .max(100, 'Name must be 100 characters or less'),
  description: z.string().max(1000).optional(),
  type: z.enum(['film', 'game', 'animation', 'mixed']),
  visibility: z.enum(['private', 'team', 'public']).default('private'),
});

type CreateProjectInput = z.infer<typeof CreateProjectSchema>;
```

#### Consistent response format

```typescript
// Success with data
{
  "success": true,
  "data": { ... }
}

// Success with message
{
  "success": true,
  "message": "Project deleted successfully"
}

// Error
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input",
    "details": {
      "name": ["Name is required"]
    }
  }
}
```

### Error Handling

#### Use custom error classes

```typescript
// errors/api-error.ts
export class ApiError extends Error {
  constructor(
    public code: string,
    message: string,
    public statusCode: number = 500,
    public details?: Record<string, unknown>
  ) {
    super(message);
    this.name = 'ApiError';
  }

  static badRequest(
    code: string,
    message: string,
    details?: Record<string, unknown>
  ) {
    return new ApiError(code, message, 400, details);
  }

  static unauthorized(message = 'Unauthorized') {
    return new ApiError('UNAUTHORIZED', message, 401);
  }

  static forbidden(message = 'Forbidden') {
    return new ApiError('FORBIDDEN', message, 403);
  }

  static notFound(resource: string) {
    return new ApiError('NOT_FOUND', `${resource} not found`, 404);
  }
}
```

#### Handle errors at boundaries

```typescript
// Hono error handler
app.onError((err, c) => {
  if (err instanceof ApiError) {
    return c.json(
      {
        success: false,
        error: {
          code: err.code,
          message: err.message,
          details: err.details,
        },
      },
      err.statusCode
    );
  }

  // Log unexpected errors
  console.error('Unexpected error:', err);

  return c.json(
    {
      success: false,
      error: {
        code: 'INTERNAL_ERROR',
        message: 'An unexpected error occurred',
      },
    },
    500
  );
});
```

---

## Database Guidelines

### Schema Design

#### Use UUIDs for primary keys

```prisma
model Project {
  id        String   @id @default(uuid())
  name      String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}
```

#### Include audit fields

```prisma
model Project {
  id        String    @id @default(uuid())
  name      String

  // Audit fields
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
  deletedAt DateTime? // Soft delete

  // Relationships
  createdBy   User   @relation("CreatedProjects", fields: [createdById], references: [id])
  createdById String
}
```

### Queries

#### Use select to limit fields

```typescript
// Good - only fetch needed fields
const users = await db.user.findMany({
  select: {
    id: true,
    name: true,
    email: true,
  },
});

// Avoid - fetching everything
const users = await db.user.findMany();
```

#### Use transactions for related operations

```typescript
await db.$transaction(async (tx) => {
  const project = await tx.project.create({
    data: { name, ownerId },
  });

  await tx.projectMember.create({
    data: {
      projectId: project.id,
      userId: ownerId,
      role: 'owner',
    },
  });

  await tx.activityLog.create({
    data: {
      type: 'project.created',
      projectId: project.id,
      userId: ownerId,
    },
  });

  return project;
});
```

---

## Testing Guidelines

### Test Structure

```typescript
import { describe, it, expect, beforeEach, vi } from 'vitest';

describe('UserService', () => {
  // Setup
  let service: UserService;
  let mockDb: MockDatabase;

  beforeEach(() => {
    mockDb = createMockDatabase();
    service = new UserService(mockDb);
  });

  // Group related tests
  describe('createUser', () => {
    it('should create user with valid input', async () => {
      // Arrange
      const input = { email: 'test@example.com', name: 'Test' };

      // Act
      const user = await service.createUser(input);

      // Assert
      expect(user).toMatchObject({
        email: 'test@example.com',
        name: 'Test',
      });
      expect(user.id).toBeDefined();
    });

    it('should throw on duplicate email', async () => {
      // Arrange
      await service.createUser({ email: 'test@example.com', name: 'Test' });

      // Act & Assert
      await expect(
        service.createUser({ email: 'test@example.com', name: 'Another' })
      ).rejects.toThrow('Email already registered');
    });
  });
});
```

### Naming Tests

Use descriptive test names that explain the behavior:

```typescript
// Good
it('should return empty array when no projects exist', () => {});
it('should throw ValidationError when name exceeds 100 characters', () => {});
it('should send email notification after user registration', () => {});

// Bad
it('test1', () => {});
it('works', () => {});
it('handles error', () => {});
```

### Mocking

```typescript
import { vi } from 'vitest';

// Mock modules
vi.mock('@yemaya/database', () => ({
  db: {
    user: {
      findUnique: vi.fn(),
      create: vi.fn(),
    },
  },
}));

// Mock functions
const mockSendEmail = vi.fn();
vi.mock('./email-service', () => ({
  sendEmail: mockSendEmail,
}));

// Reset between tests
beforeEach(() => {
  vi.clearAllMocks();
});
```

---

## Git Workflow

### Commit Messages

Follow [Conventional Commits](https://www.conventionalcommits.org/):

```
<type>(<scope>): <description>

[optional body]

[optional footer]
```

**Types:** feat, fix, docs, style, refactor, test, chore

**Examples:**

```
feat(api): add project archiving endpoint

fix(web): resolve login redirect loop
Fixes #456

docs(readme): update installation instructions

refactor(database): extract query builders into separate module

test(auth): add integration tests for OAuth flow

chore(deps): upgrade vitest to v1.0
```

### Branch Strategy

```
main
├── develop
│   ├── feature/add-user-avatars
│   ├── feature/project-templates
│   └── fix/upload-memory-leak
└── release/v1.2.0
```

---

## Tooling

### ESLint

We use ESLint with custom rules. Run:

```bash
pnpm lint        # Check
pnpm lint:fix    # Auto-fix
```

### Prettier

Code formatting is handled by Prettier:

```bash
pnpm format      # Format all files
```

### TypeScript

Type checking:

```bash
pnpm typecheck   # Check all packages
```

### Pre-commit Hooks

Husky runs checks before commits:

1. Lint staged files
2. Type check
3. Run affected tests

---

## Questions?

If you're unsure about a style decision:

1. Check existing code for patterns
2. Ask in the Discord #development channel
3. Open a discussion on GitHub

Remember: consistency is more important than any specific rule. When in doubt,
match the surrounding code.
