# /api — Generate API Route Boilerplate

Scaffold Next.js App Router API routes following mawidi patterns: Prisma ORM, Zod validation, NextAuth session, rate limiting, input sanitization.

## Usage

```
/api create <resource>                 # Full CRUD (list, get, create, update, delete)
/api route <METHOD> <path>             # Single route
/api schema <modelName>                # Prisma model + Zod validation schema
/api middleware <name>                 # Custom middleware/utility
/api docs                              # Generate API documentation
```

**Examples:**
- `/api create invoices`
- `/api route POST /api/bookings/cancel`
- `/api schema Invoice`
- `/api middleware rate-limit`

## Patterns to Follow

### Directory Structure
API routes live in `app/api/` following Next.js App Router conventions:
```
app/api/<resource>/
  route.ts           # GET (list) + POST (create)
  [id]/
    route.ts         # GET (single) + PUT (update) + DELETE
```

### Standard Route Template
Every route should include:

```typescript
import { NextRequest, NextResponse } from 'next/server';
import { getAuthSession } from '@/lib/auth-session';
import { prisma } from '@/lib/prisma'; // or appropriate db import
import { z } from 'zod';
import { createRateLimiter } from '@/lib/rate-limiter';
import { sanitizeInput } from '@/lib/input-validation';

// Zod validation schema
const createSchema = z.object({
  // fields...
});

// Rate limiter
const limiter = createRateLimiter({ maxRequests: 10, windowMs: 60000 });

export async function POST(request: NextRequest) {
  try {
    // 1. Rate limit
    const rateLimitResult = await limiter.check(request);
    if (!rateLimitResult.allowed) {
      return NextResponse.json({ error: 'Too many requests' }, { status: 429 });
    }

    // 2. Auth check
    const session = await getAuthSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // 3. Parse and validate body
    const body = await request.json();
    const validated = createSchema.parse(body);

    // 4. Sanitize inputs
    const sanitized = sanitizeInput(validated);

    // 5. Business logic with Prisma
    const result = await prisma.resource.create({
      data: { ...sanitized, userId: session.user.id },
    });

    // 6. Return response
    return NextResponse.json(result, { status: 201 });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: 'Validation failed', details: error.errors }, { status: 400 });
    }
    console.error('[API] Error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
```

### CRUD Template (`/api create <resource>`)

Creates two files:
1. `app/api/<resource>/route.ts` — GET (list) + POST (create)
2. `app/api/<resource>/[id]/route.ts` — GET (single) + PUT + DELETE

Plus:
3. `lib/validators/<resource>.validator.ts` — Zod schemas
4. `lib/services/<resource>.service.ts` — Business logic service

### Schema Template (`/api schema <model>`)

Creates:
1. Adds model to `prisma/schema.prisma`
2. Creates `lib/validators/<model>.validator.ts` with Zod schemas
3. Runs `npx prisma generate`

## Key Patterns from Existing Code
- Auth: `getAuthSession()` from `@/lib/auth-session`
- DB: Prisma client (check existing import pattern in the codebase)
- Validation: Zod schemas in `lib/validators/`
- Services: Business logic in `lib/services/`
- Rate limiting: `createRateLimiter` from `@/lib/rate-limiter`
- Input sanitization: `sanitizeInput` from `@/lib/input-validation`
- Error responses: Consistent JSON format with `{ error: string }`
- Status codes: 200 (success), 201 (created), 400 (validation), 401 (unauth), 403 (forbidden), 404 (not found), 429 (rate limit), 500 (server error)

## Key Rules
- ALWAYS check existing patterns in the codebase before scaffolding
- ALWAYS include auth checks on protected routes
- ALWAYS include Zod validation
- ALWAYS include rate limiting
- ALWAYS sanitize user inputs
- Follow existing file naming conventions
- Use Prisma, not raw SQL
- Add Arabic/English error messages where applicable
