# GraphQL API Reference

This document provides comprehensive documentation for the Lilith GraphQL API.

## Overview

The Lilith GraphQL API provides a flexible, type-safe interface for content
management, entity relationships, and knowledge graph operations. Built on
Mercurius (Fastify GraphQL plugin), it supports queries, mutations,
subscriptions, and real-time updates.

**Endpoint**: `https://api.lilith.ai/graphql` **Playground**:
`https://api.lilith.ai/graphiql` **WebSocket**: `wss://api.lilith.ai/graphql`

## Quick Start

### Basic Query

```graphql
query GetContent {
  content(id: "content_123") {
    id
    title
    slug
    summary
    status
    author {
      id
      name
      tradition
    }
    metadata {
      language
      tradition
      era
      readingTime
    }
  }
}
```

### HTTP Request

```bash
curl -X POST https://api.lilith.ai/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <token>" \
  -d '{
    "query": "query { content(id: \"content_123\") { id title } }"
  }'
```

---

## Custom Scalars

### DateTime

ISO 8601 date-time string.

```graphql
scalar DateTime
```

**Examples**:

- `"2024-01-15T10:30:00.000Z"`
- `"2024-03-20T14:45:30+05:30"`

### JSON

Arbitrary JSON data.

```graphql
scalar JSON
```

---

## Enums

### ContentType

```graphql
enum ContentType {
  TEXT
  SUTRA
  COMMENTARY
  LECTURE
  MEDITATION
  TEACHING
  POEM
  PRAYER
  MANTRA
  STORY
  BIOGRAPHY
}
```

### ContentStatus

```graphql
enum ContentStatus {
  DRAFT
  REVIEW
  PUBLISHED
  ARCHIVED
}
```

### Visibility

```graphql
enum Visibility {
  PUBLIC
  PRIVATE
  PREMIUM
  RESTRICTED
}
```

### DifficultyLevel

```graphql
enum DifficultyLevel {
  BEGINNER
  INTERMEDIATE
  ADVANCED
  SCHOLARLY
}
```

### DateCertainty

```graphql
enum DateCertainty {
  EXACT
  APPROXIMATE
  RANGE
  CENTURY
  UNKNOWN
}
```

### CitationStyle

```graphql
enum CitationStyle {
  CHICAGO
  MLA
  APA
  TURABIAN
}
```

### EntityType

```graphql
enum EntityType {
  PERSON
  PLACE
  CONCEPT
  EVENT
  TEXT
  TRADITION
  SCHOOL
  DEITY
  SYMBOL
}
```

### RelationshipType

```graphql
enum RelationshipType {
  REFERENCES
  CITES
  RESPONDS_TO
  INFLUENCES
  INFLUENCED_BY
  TEACHER_OF
  STUDENT_OF
  BELONGS_TO
  LOCATED_IN
  CONTEMPORARY_OF
  ASSOCIATED_WITH
}
```

### SortDirection

```graphql
enum SortDirection {
  ASC
  DESC
}
```

### ContentSortField

```graphql
enum ContentSortField {
  TITLE
  CREATED_AT
  UPDATED_AT
  PUBLISHED_AT
  VIEWS
  RELEVANCE
}
```

---

## Object Types

### Content

Primary content object for scholarly texts.

```graphql
type Content {
  id: ID!
  slug: String!
  title: String!
  summary: String
  body: String
  contentType: ContentType!
  status: ContentStatus!
  visibility: Visibility!
  author: Author
  metadata: ContentMetadata
  citations: [Citation!]
  tags: [String!]
  version: Int!
  versions: [ContentVersion!]
  createdAt: DateTime!
  updatedAt: DateTime!
  publishedAt: DateTime
}
```

### Author

Author/contributor information.

```graphql
type Author {
  id: ID!
  name: String!
  slug: String!
  biography: String
  tradition: String
  era: String
  birthYear: Int
  deathYear: Int
  imageUrl: String
  content: [Content!]
  createdAt: DateTime!
  updatedAt: DateTime!
}
```

### ContentMetadata

Rich metadata for scholarly content.

```graphql
type ContentMetadata {
  language: String
  originalLanguage: String
  tradition: String
  era: String
  genre: String
  tags: [String!]
  dateComposed: DateRange
  location: Location
  wordCount: Int
  readingTime: Int
  difficulty: DifficultyLevel
}
```

### Entity

Knowledge graph entity.

```graphql
type Entity {
  id: ID!
  name: String!
  slug: String!
  type: EntityType!
  description: String
  properties: [EntityProperty!]
  relationships: [Relationship!]
  incomingRelationships: [Relationship!]
  metadata: JSON
  createdAt: DateTime!
  updatedAt: DateTime!
}
```

### EntityProperty

Entity attribute key-value pair.

```graphql
type EntityProperty {
  key: String!
  value: String!
  dataType: PropertyDataType!
}
```

### Relationship

Entity-to-entity relationship.

```graphql
type Relationship {
  id: ID!
  type: RelationshipType!
  sourceId: ID!
  targetId: ID!
  source: Entity
  target: Entity
  properties: JSON
  strength: Float
  createdAt: DateTime!
  updatedAt: DateTime!
}
```

### Citation

Source citation information.

```graphql
type Citation {
  id: ID!
  style: CitationStyle!
  title: String!
  author: String
  year: Int
  source: String
  url: String
  doi: String
  isbn: String
  pages: String
  formatted: String
}
```

### ContentVersion

Version history entry.

```graphql
type ContentVersion {
  version: Int!
  title: String!
  body: String
  changedBy: String
  changedAt: DateTime!
  changeNote: String
}
```

---

## Connection Types (Pagination)

The API uses Relay-style cursor-based pagination.

### ContentConnection

```graphql
type ContentConnection {
  edges: [ContentEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type ContentEdge {
  node: Content!
  cursor: String!
}
```

### EntityConnection

```graphql
type EntityConnection {
  edges: [EntityEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type EntityEdge {
  node: Entity!
  cursor: String!
}
```

### AuthorConnection

```graphql
type AuthorConnection {
  edges: [AuthorEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type AuthorEdge {
  node: Author!
  cursor: String!
}
```

### PageInfo

```graphql
type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}
```

---

## Queries

### Content Queries

#### Get Single Content

```graphql
query {
  content(id: ID!): Content
}
```

#### Get Content by Slug

```graphql
query {
  contentBySlug(slug: String!): Content
}
```

#### List Contents with Filtering

```graphql
query {
  contents(
    filter: ContentFilterInput
    sort: ContentSortInput
    first: Int
    after: String
    last: Int
    before: String
  ): ContentConnection!
}
```

**ContentFilterInput**:

| Field             | Type              | Description              |
| ----------------- | ----------------- | ------------------------ |
| `contentType`     | `ContentType`     | Filter by type           |
| `status`          | `ContentStatus`   | Filter by status         |
| `visibility`      | `Visibility`      | Filter by visibility     |
| `authorId`        | `ID`              | Filter by author         |
| `tradition`       | `String`          | Filter by tradition      |
| `era`             | `String`          | Filter by era            |
| `language`        | `String`          | Filter by language       |
| `tags`            | `[String!]`       | Filter by tags           |
| `tagsMatch`       | `TagsMatch`       | `ALL` or `ANY` tag match |
| `difficulty`      | `DifficultyLevel` | Filter by difficulty     |
| `search`          | `String`          | Full-text search         |
| `publishedAfter`  | `DateTime`        | Published date filter    |
| `publishedBefore` | `DateTime`        | Published date filter    |

**Example**:

```graphql
query BuddhistTexts {
  contents(
    filter: {
      tradition: "Buddhism"
      status: PUBLISHED
      difficulty: INTERMEDIATE
    }
    sort: { field: PUBLISHED_AT, direction: DESC }
    first: 10
  ) {
    edges {
      node {
        id
        title
        summary
        author {
          name
        }
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
    totalCount
  }
}
```

#### Search Content

```graphql
query {
  searchContent(
    query: String!
    filter: ContentFilterInput
    first: Int
    after: String
  ): SearchResult!
}
```

**SearchResult**:

```graphql
type SearchResult {
  edges: [ContentEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
  facets: SearchFacets
  suggestions: [SearchSuggestion!]
}

type SearchFacets {
  traditions: [FacetItem!]
  eras: [FacetItem!]
  types: [FacetItem!]
  languages: [FacetItem!]
  difficulties: [FacetItem!]
}

type FacetItem {
  value: String!
  count: Int!
}
```

**Example**:

```graphql
query SearchMeditation {
  searchContent(query: "mindfulness meditation", first: 20) {
    edges {
      node {
        title
        summary
        metadata {
          tradition
          difficulty
        }
      }
    }
    facets {
      traditions {
        value
        count
      }
    }
    totalCount
  }
}
```

#### Get Search Suggestions

```graphql
query {
  suggestions(prefix: String!, limit: Int): [SearchSuggestion!]!
}
```

### Author Queries

#### Get Author

```graphql
query {
  author(id: ID!): Author
}
```

#### List Authors

```graphql
query {
  authors(
    tradition: String
    era: String
    first: Int
    after: String
  ): AuthorConnection!
}
```

### Entity Queries

#### Get Entity

```graphql
query {
  entity(id: ID!): Entity
}
```

#### List Entities

```graphql
query {
  entities(
    filter: EntityFilterInput
    first: Int
    after: String
  ): EntityConnection!
}
```

**EntityFilterInput**:

| Field    | Type            | Description            |
| -------- | --------------- | ---------------------- |
| `types`  | `[EntityType!]` | Filter by entity types |
| `search` | `String`        | Search entity names    |

#### Get Entity Types

```graphql
query {
  entityTypes: [EntityType!]!
}
```

### Relationship Queries

#### Get Relationship

```graphql
query {
  relationship(id: ID!): Relationship
}
```

#### Get Entity Relationships

```graphql
query {
  relationshipsByEntity(
    entityId: ID!
    type: RelationshipType
    direction: String  # "outgoing" | "incoming" | "both"
  ): [Relationship!]!
}
```

#### Get Relationship Types

```graphql
query {
  relationshipTypes: [RelationshipType!]!
}
```

### Knowledge Graph Queries

#### Traverse Knowledge Graph

```graphql
query {
  knowledgeGraph(
    entityId: ID!
    depth: Int
    relationshipTypes: [RelationshipType!]
  ): KnowledgeGraphResult!
}
```

**KnowledgeGraphResult**:

```graphql
type KnowledgeGraphResult {
  entities: [Entity!]!
  relationships: [Relationship!]!
  metadata: KnowledgeGraphMetadata!
}

type KnowledgeGraphMetadata {
  totalEntities: Int!
  totalRelationships: Int!
  maxDepthReached: Int!
  traversalTime: Float!
}
```

**Example**:

```graphql
query BuddhaInfluences {
  knowledgeGraph(
    entityId: "entity_buddha"
    depth: 2
    relationshipTypes: [INFLUENCES, TEACHER_OF]
  ) {
    entities {
      id
      name
      type
    }
    relationships {
      type
      source {
        name
      }
      target {
        name
      }
    }
    metadata {
      totalEntities
      maxDepthReached
    }
  }
}
```

---

## Mutations

### Content Mutations

#### Create Content

```graphql
mutation {
  createContent(input: CreateContentInput!): Content!
}
```

**CreateContentInput**:

| Field         | Type                   | Required | Description                          |
| ------------- | ---------------------- | -------- | ------------------------------------ |
| `title`       | `String!`              | Yes      | Content title                        |
| `slug`        | `String`               | No       | URL slug (auto-generated if omitted) |
| `summary`     | `String`               | No       | Content summary                      |
| `body`        | `String`               | No       | Full content body                    |
| `contentType` | `ContentType!`         | Yes      | Content type                         |
| `visibility`  | `Visibility`           | No       | Visibility level                     |
| `authorId`    | `ID`                   | No       | Author reference                     |
| `metadata`    | `ContentMetadataInput` | No       | Content metadata                     |
| `tags`        | `[String!]`            | No       | Content tags                         |

**Example**:

```graphql
mutation CreateSutra {
  createContent(
    input: {
      title: "The Heart Sutra Commentary"
      contentType: COMMENTARY
      summary: "A modern interpretation of the Prajñāpāramitā Hṛdaya"
      body: "..."
      visibility: PUBLIC
      metadata: {
        tradition: "Buddhism"
        language: "en"
        difficulty: INTERMEDIATE
      }
      tags: ["Buddhism", "Mahayana", "Wisdom"]
    }
  ) {
    id
    slug
    status
  }
}
```

#### Update Content

```graphql
mutation {
  updateContent(id: ID!, input: UpdateContentInput!): Content!
}
```

#### Delete Content

```graphql
mutation {
  deleteContent(id: ID!): DeleteResult!
}
```

#### Publish Content

```graphql
mutation {
  publishContent(id: ID!): Content!
}
```

#### Archive Content

```graphql
mutation {
  archiveContent(id: ID!): Content!
}
```

#### Restore Content Version

```graphql
mutation {
  restoreContentVersion(id: ID!, version: Int!): Content!
}
```

#### Bulk Content Operations

```graphql
mutation {
  bulkContentOperation(
    operation: BulkOperation!
    inputs: [BulkContentInput!]!
  ): BulkOperationResult!
}
```

**BulkOperation Enum**:

```graphql
enum BulkOperation {
  CREATE
  UPDATE
  DELETE
  PUBLISH
  ARCHIVE
}
```

**BulkOperationResult**:

```graphql
type BulkOperationResult {
  success: Boolean!
  processed: Int!
  failed: Int!
  results: [Content!]
  failures: [BulkFailure!]
}

type BulkFailure {
  index: Int!
  error: String!
}
```

### Author Mutations

#### Create Author

```graphql
mutation {
  createAuthor(input: CreateAuthorInput!): Author!
}
```

**CreateAuthorInput**:

| Field       | Type      | Required | Description    |
| ----------- | --------- | -------- | -------------- |
| `name`      | `String!` | Yes      | Author name    |
| `slug`      | `String`  | No       | URL slug       |
| `biography` | `String`  | No       | Biography      |
| `tradition` | `String`  | No       | Tradition      |
| `era`       | `String`  | No       | Historical era |
| `birthYear` | `Int`     | No       | Birth year     |
| `deathYear` | `Int`     | No       | Death year     |
| `imageUrl`  | `String`  | No       | Profile image  |

#### Update Author

```graphql
mutation {
  updateAuthor(id: ID!, input: CreateAuthorInput!): Author!
}
```

#### Delete Author

```graphql
mutation {
  deleteAuthor(id: ID!): DeleteResult!
}
```

### Entity Mutations

#### Create Entity

```graphql
mutation {
  createEntity(input: CreateEntityInput!): Entity!
}
```

**CreateEntityInput**:

| Field         | Type                     | Required | Description         |
| ------------- | ------------------------ | -------- | ------------------- |
| `name`        | `String!`                | Yes      | Entity name         |
| `slug`        | `String`                 | No       | URL slug            |
| `type`        | `EntityType!`            | Yes      | Entity type         |
| `description` | `String`                 | No       | Description         |
| `properties`  | `[EntityPropertyInput!]` | No       | Properties          |
| `metadata`    | `JSON`                   | No       | Additional metadata |

**Example**:

```graphql
mutation CreatePhilosopher {
  createEntity(
    input: {
      name: "Nagarjuna"
      type: PERSON
      description: "Indian Mahayana Buddhist philosopher"
      properties: [
        { key: "birthCentury", value: "2", dataType: INTEGER }
        { key: "tradition", value: "Madhyamaka", dataType: STRING }
      ]
    }
  ) {
    id
    slug
    type
  }
}
```

#### Update Entity

```graphql
mutation {
  updateEntity(id: ID!, input: CreateEntityInput!): Entity!
}
```

#### Delete Entity

```graphql
mutation {
  deleteEntity(id: ID!): DeleteResult!
}
```

### Relationship Mutations

#### Create Relationship

```graphql
mutation {
  createRelationship(input: CreateRelationshipInput!): Relationship!
}
```

**CreateRelationshipInput**:

| Field        | Type                | Required | Description                 |
| ------------ | ------------------- | -------- | --------------------------- |
| `type`       | `RelationshipType!` | Yes      | Relationship type           |
| `sourceId`   | `ID!`               | Yes      | Source entity ID            |
| `targetId`   | `ID!`               | Yes      | Target entity ID            |
| `properties` | `JSON`              | No       | Relationship properties     |
| `strength`   | `Float`             | No       | Relationship strength (0-1) |

**Example**:

```graphql
mutation CreateInfluence {
  createRelationship(
    input: {
      type: INFLUENCES
      sourceId: "entity_nagarjuna"
      targetId: "entity_chandrakirti"
      strength: 0.9
      properties: { domain: "philosophy", evidence: "direct lineage" }
    }
  ) {
    id
    type
    source {
      name
    }
    target {
      name
    }
  }
}
```

#### Update Relationship

```graphql
mutation {
  updateRelationship(
    id: ID!
    properties: JSON
    strength: Float
  ): Relationship!
}
```

#### Delete Relationship

```graphql
mutation {
  deleteRelationship(id: ID!): DeleteResult!
}
```

---

## Subscriptions

Real-time updates via WebSocket.

### Content Subscriptions

#### Content Updated

```graphql
subscription {
  contentUpdated(contentId: ID): ContentUpdateEvent!
}
```

**ContentUpdateEvent**:

```graphql
type ContentUpdateEvent {
  type: ContentUpdateType!
  content: Content!
  timestamp: DateTime!
  changedFields: [String!]
}

enum ContentUpdateType {
  CREATED
  UPDATED
  PUBLISHED
  ARCHIVED
  DELETED
}
```

#### Content Created

```graphql
subscription {
  contentCreated(contentType: ContentType): Content!
}
```

#### Content Published

```graphql
subscription {
  contentPublished(tradition: String): Content!
}
```

### Entity Subscriptions

#### Entity Updated

```graphql
subscription {
  entityUpdated(entityType: EntityType): EntityUpdateEvent!
}
```

**EntityUpdateEvent**:

```graphql
type EntityUpdateEvent {
  type: EntityUpdateType!
  entity: Entity!
  timestamp: DateTime!
}

enum EntityUpdateType {
  CREATED
  UPDATED
  DELETED
  RELATIONSHIP_ADDED
  RELATIONSHIP_REMOVED
}
```

### Subscription Example

```javascript
import { createClient } from 'graphql-ws';

const client = createClient({
  url: 'wss://api.lilith.ai/graphql',
  connectionParams: {
    authorization: `Bearer ${token}`,
  },
});

// Subscribe to content updates
const unsubscribe = client.subscribe(
  {
    query: `
      subscription {
        contentUpdated {
          type
          content {
            id
            title
            status
          }
          timestamp
        }
      }
    `,
  },
  {
    next: (data) => {
      console.log('Content updated:', data);
    },
    error: (err) => {
      console.error('Subscription error:', err);
    },
    complete: () => {
      console.log('Subscription complete');
    },
  }
);

// Later: unsubscribe
unsubscribe();
```

---

## Error Handling

### Error Response Format

```json
{
  "data": null,
  "errors": [
    {
      "message": "Content not found",
      "locations": [{ "line": 2, "column": 3 }],
      "path": ["content"],
      "extensions": {
        "code": "NOT_FOUND",
        "timestamp": "2024-01-15T10:30:00.000Z"
      }
    }
  ]
}
```

### Error Codes

| Code               | Description                              |
| ------------------ | ---------------------------------------- |
| `NOT_FOUND`        | Resource not found                       |
| `UNAUTHORIZED`     | Authentication required                  |
| `FORBIDDEN`        | Insufficient permissions                 |
| `VALIDATION_ERROR` | Invalid input data                       |
| `CONFLICT`         | Resource conflict (e.g., duplicate slug) |
| `INTERNAL_ERROR`   | Server error                             |

---

## Pagination

The API uses Relay-style cursor-based pagination.

### Forward Pagination

```graphql
query {
  contents(first: 10, after: "cursor123") {
    edges {
      node {
        id
        title
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

### Backward Pagination

```graphql
query {
  contents(last: 10, before: "cursor456") {
    edges {
      node {
        id
        title
      }
      cursor
    }
    pageInfo {
      hasPreviousPage
      startCursor
    }
  }
}
```

### Pagination Best Practices

1. Use `first`/`after` for forward pagination
2. Store `endCursor` for next page requests
3. Check `hasNextPage` before fetching more
4. Default page size: 20, max: 100

---

## Rate Limiting

| Operation     | Limit             |
| ------------- | ----------------- |
| Queries       | 100/minute        |
| Mutations     | 50/minute         |
| Subscriptions | 10 concurrent     |
| Complexity    | 1000 points/query |

### Complexity Calculation

- Each field: 1 point
- Connections: 10 points + (first × child complexity)
- Nested resolvers: Multiplicative

---

## Best Practices

### Query Optimization

```graphql
# DO: Request only needed fields
query {
  contents(first: 10) {
    edges {
      node {
        id
        title
      }
    }
  }
}

# DON'T: Over-fetch
query {
  contents(first: 100) {
    edges {
      node {
        id
        title
        body # Large field
        versions # Expensive nested query
        author {
          content # N+1 query
        }
      }
    }
  }
}
```

### Batching Requests

```graphql
# Batch multiple queries
query BatchedQueries {
  content1: content(id: "id1") {
    title
  }
  content2: content(id: "id2") {
    title
  }
  content3: content(id: "id3") {
    title
  }
}
```

### Fragment Reuse

```graphql
fragment ContentSummary on Content {
  id
  title
  summary
  status
}

query {
  recentContent: contents(
    first: 5
    sort: { field: CREATED_AT, direction: DESC }
  ) {
    edges {
      node {
        ...ContentSummary
      }
    }
  }
  popularContent: contents(first: 5, sort: { field: VIEWS, direction: DESC }) {
    edges {
      node {
        ...ContentSummary
      }
    }
  }
}
```

---

## Related Documentation

- [TypeScript SDK Reference](./typescript-sdk.md) - SDK with GraphQL client
- [Authentication Guide](./authentication.md) - API authentication
- [Error Codes](./error-codes.md) - Complete error reference
- [API Versioning](./api-versioning.md) - Version management

---

## GraphQL Playground

Access the interactive GraphQL IDE at:

- **Development**: http://localhost:8080/graphiql
- **Production**: https://api.lilith.ai/graphiql

Features:

- Schema explorer
- Auto-complete
- Query history
- Variable editor
- Response viewer
