# Data Modeling

## Core Concepts

At the heart of this data modeling system are the following fundamental concepts.

### DomainNamespace

This is the top-level container, representing a logical grouping of data. Think of it as a "domain" or a "schema" in a database. It can contain:

- `DomainModels`: Logical groupings of entities.
- `DataEntities`: The basic building blocks, representing individual data structures.
- `DataProperties`: Attributes of entities (e.g., name, age, address).
- `DomainAssociations`: Relationships between entities (e.g., a user has an address).
- `Sub-namespaces`: Namespaces can be nested within each other, creating a hierarchical structure.
- `Foreign Namespaces`: References to external namespaces, enabling the use of entities defined elsewhere.
- `Tags`: Common tags for the entire namespace.

### DomainModel

A logical grouping of `DomainEntity` instances. It represents a specific data structure, like a "Product" or "User" model. A `DomainModel` can contain multiple `DomainEntity` instances.

### DomainEntity

The fundamental building block of the data model. It represents a specific type of data, like a "User," "Product," or "Address."

- `Properties`: DomainProperty instances that describe the attributes of the entity.
- `Associations`: DomainAssociation instances that define relationships to other entities.
- `Parents`: An entity can inherit from other entities, creating a hierarchy.
- `Fields`: Ordered list of properties and associations.
- `Tags`: Optional tags for the UI.
- `Semantics`: A system of predefined, meaningful labels or classifications that can be applied to Data Entities or their individual properties.
- `Deprecated`: Whether the entity is deprecated.
- `Schema`: The schema allowing to translate the model into a specific format (like JSON, RAML, XML, etc.)

### DomainProperty

Represents an attribute of a `DomainEntity`. It has a name, a data type (e.g., string, number, boolean), and optional constraints (e.g., required, multiple, min/max values).

- `Type`: The data type of the property.
- `Schema`: The general schema definition of this property.
- `Bindings`: The list of bindings for this property.
- `Tags`: Optional tags for the UI.
- `Semantics`: A system of predefined, meaningful labels or classifications that can be applied to Data Entities or their individual properties.
- `Deprecated`: Whether the property is deprecated.
- `Primary`: Whether this property describes a primary key of the entity.
- `Index`: Whether this property describes an indexed property of the entity.
- `ReadOnly`: Whether the property is read only in the schema.
- `WriteOnly`: Whether the property is write only in the schema.

### DomainAssociation

Defines a relationship between `DomainEntity` instances. It specifies the target entities and the nature of the relationship (e.g., one-to-one, one-to-many).

- `Targets`: The list of target entities.
- `Multiple`: Whether the association allows multiple target entities.
- `Required`: Whether the association is required.
- `Schema`: The definition of the database/API schema
- `Bindings`: The list of bindings allowing to translate the model into a specific format (like JSON, RAML, XML, etc.)
- `Hidden`: Defines if this association is a part of the schema or not.

### Bindings

Defines a translation from a data model to a specific format (like JSON, RAML, XML, etc.)

## How a Data Domain is Structured

Here's how these components work together to structure a data domain:

1. **Root Namespace**: You start with a `DomainNamespace`, which acts as the root of your data domain. This namespace is the top-level container for all other elements.

1. **Sub-namespaces (Optional)**: You can create sub-namespaces within the root namespace to further organize your data. This is useful for large domains with many entities and relationships.

1. **Data Models**: Within a namespace (or sub-namespace), you define `DomainModel` instances. Each `DomainModel` represents a specific area of your domain. For example, you might have a "User Management" `DomainModel`, a "Product Catalog" `DomainModel`, and an "Order Processing" `DomainModel`.

1. **Data Entities**: Inside each `DomainModel`, you define `DomainEntity` instances. These are the core data structures. For example, in the "User Management" `DomainModel`, you might have `DomainEntity` instances for "User," "Role," and "Permission."

1. **Data Properties**: Each `DomainEntity` has `DomainProperty` instances that describe its attributes. For example, the "User" `DomainEntity` might have `DomainProperty` instances for "firstName" (string), "lastName" (string), "email" (string), "age" (number), etc.

1. **Data Associations**: You use `DomainAssociation` instances to define relationships between `DomainEntity` instances. For example:

   - A "User" has an "Address" (one-to-one).
   - A "User" has multiple "Roles" (one-to-many).
   - A "Product" belongs to a "Category" (many-to-one).
   - An "Order" contains multiple "Order Items" (one-to-many).

1. **Inheritance**: `DomainEntity` instances can inherit from other `DomainEntity` instances using the parents property. This allows you to create a hierarchy of entities and reuse common properties and associations.

1. **Foreign Namespaces**: You can reference entities from other namespaces using the foreign property of the root namespace. This allows you to reuse data structures defined elsewhere.

1. **Bindings**: You can define bindings for properties and associations to translate the data model into specific formats (e.g., JSON, RAML, XML, Protocol Buffers).

## Example Scenario

Let's imagine a simple e-commerce domain:

- **Root Namespace**: `ECommerce`
  - **Sub-namespace**: `Catalog`
    - **Data Model**: `ProductCatalog`
      - **Data Entity**: `Product`
        - **Data Properties**: `name` (string), `description` (string), `price` (number), `sku` (string)
        - **Data Association**: `category` (references `Category` entity)
      - **Data Entity**: `Category`
        - **Data Properties**: `name` (string), `description` (string)
  - **Sub-namespace**: `UserManagement`
    - **Data Model**: `UserManagement`
      - **Data Entity**: `User`
        - **Data Properties**: `firstName` (string), `lastName` (string), `email` (string), `password` (string)
        - **Data Association**: `address` (references `Address` entity)
      - **Data Entity**: `Address`
        - **Data Properties**: `street` (string), `city` (string), `zipCode` (string), `country` (string)
  - **Foreign Namespace**: `Semantics` (defined elsewhere)
    - **Data Model**: `Semantics`
      - **Data Entity**: `SemanticsItem`

### Key Relationships

- **Namespace-Model**: A `DomainNamespace` contains `DomainModel` instances.
- **Model-Entity**: A `DomainModel` contains `DomainEntity` instances.
- **Entity-Property**: A `DomainEntity` has `DomainProperty` instances.
- **Entity-Association**: A `DomainEntity` has `DomainAssociation` instances.
- **Entity-Parent**: A `DomainEntity` can have `DomainEntity` instances as parents.
- **Namespace-Foreign**: A `DomainNamespace` can have references to `DomainNamespace` instances.

## API Modeling

Beyond data modeling, the system also provides **API Modeling** capabilities that allow you to define how your data domain is exposed as a secure, production-ready API.

### ApiModel

The `ApiModel` class extends the data modeling system to define how Data Entities from a `DataDomain` are exposed via HTTP APIs. It provides configuration for:

**Core API Configuration:**

- **Exposed Entities**: Select which Data Entities from your Data Domain should be accessible via the API
- **API Actions**: Define what operations (List, Read, Create, Update, Delete, Search) are available for each entity
- **User Entity**: Designate which Data Entity represents a "User" for authentication purposes

**Security & Authentication:**

- **Authentication**: Configure how users prove their identity (e.g., username/password)
- **Authorization**: Define what authenticated users are allowed to do (e.g., Role-Based Access Control)
- **Session Management**: Configure transport and payload for user sessions (JWT, cookies)
- **Access Rules**: Define fine-grained access control policies for entities and actions

**API Metadata:**

- **Contact Information**: API maintainer details
- **License Information**: Legal information about API usage
- **Terms of Service**: Link to API usage terms
- **Rate Limiting**: Protect the API from overuse and abuse

### How API Modeling Works with Data Modeling

The API modeling system builds on top of the data modeling foundation:

1. **Start with a Data Domain**: Create your `DataDomain` with entities, properties, and associations
2. **Create an API Model**: Instantiate an `ApiModel` and attach your `DataDomain`
3. **Expose Entities**: Select which entities should be available via the API using `exposeEntity()`
4. **Configure Security**: Set up authentication, authorization, and session management
5. **Define Actions**: Configure what operations are available for each exposed entity
6. **Set API Metadata**: Add contact info, license, terms of service

### Example: E-Commerce API

Building on the e-commerce data domain example:

```typescript
// 1. Create the data domain (as shown in previous example)
const domain = new DataDomain({ key: 'ecommerce', info: { name: 'E-Commerce Platform' } })
const userModel = domain.addModel({ info: { name: 'User Management' } })
const userEntity = userModel.addEntity({ 
  info: { name: 'user' },
  semantics: [{ type: SemanticType.User }] // Mark as User entity
})

// 2. Create an API model
const apiModel = new ApiModel({
  info: { name: 'E-Commerce API', version: '1.0.0' },
  termsOfService: 'https://example.com/terms',
  contact: { name: 'API Team', email: 'api@example.com' },
  license: { name: 'MIT', url: 'https://opensource.org/licenses/MIT' }
})

// 3. Attach the data domain
apiModel.attachDataDomain(domain)

// 4. Configure security
apiModel.user = { key: userEntity.key }
apiModel.authentication = { strategy: 'UsernamePassword', passwordKey: 'password' }
apiModel.authorization = { strategy: 'RBAC', roleKey: 'role' }
apiModel.session = { 
  secret: 'your-secure-secret',
  properties: ['email', 'role'],
  cookie: { enabled: true, kind: 'cookie', lifetime: '7d' }
}

// 5. Expose entities and configure actions
const exposedUser = apiModel.exposeEntity(userEntity.key)
exposedUser.actions = [
  { type: 'Read', enabled: true },
  { type: 'Update', enabled: true },
  { type: 'Create', enabled: true }
]
```

### Key API Modeling Concepts

#### ExposedEntity

Represents a Data Entity that is exposed via the API. Contains:

- **Key**: Reference to the Data Entity
- **Actions**: List of available API operations (CRUD, Search)
- **Access Rules**: Entity-specific access control
- **Rate Limiting**: Entity-specific rate limiting rules

#### API Actions

Standard RESTful operations that can be enabled for each entity:

- **List**: Retrieve collections of entities with filtering and pagination
- **Read**: Retrieve a single entity by ID
- **Create**: Create new entities
- **Update**: Modify existing entities
- **Delete**: Remove entities
- **Search**: Full-text or advanced search across entities

#### Authentication Configuration

Defines how users prove their identity:

- **UsernamePassword**: Traditional email/password authentication
- Extensible for future strategies (SSO, OAuth, etc.)

#### Authorization Configuration

Defines what authenticated users can do:

- **RBAC (Role-Based Access Control)**: Users have roles, permissions granted to roles
- Extensible for future strategies (PBAC - Permission-Based Access Control)

#### Session Configuration

Manages user session data:

- **Properties**: Which User entity properties to include in session
- **Transport**: How session data is transmitted (JWT tokens, cookies)
- **Security**: Encryption, lifetime, and security settings

### Business-First API Design

The API modeling system follows the same business-first philosophy as data modeling:

- **Semantic Awareness**: Uses semantic types to automatically configure security (e.g., Password properties are write-only)
- **Standard Compliance**: Generates OpenAPI-compliant specifications
- **Security by Default**: Requires explicit configuration for authentication, authorization, and sessions
- **User-Friendly**: Clear error messages and validation feedback
- **Production Ready**: Built-in support for rate limiting, access control, and monitoring

## Summary

This comprehensive modeling system provides both **Data Modeling** and **API Modeling** capabilities:

**Data Modeling** allows you to:

- **Organize**: Group related data into namespaces and models
- **Structure**: Define entities with properties and relationships
- **Reuse**: Inherit from other entities and reference foreign namespaces
- **Translate**: Define bindings to map the model to different formats
- **Validate**: Validate the data model definition
- **Generate**: Generate AMF shapes and examples

**API Modeling** extends this to:

- **Expose**: Selectively expose Data Entities as API resources
- **Secure**: Configure authentication, authorization, and session management
- **Control**: Define fine-grained access rules and rate limiting
- **Document**: Generate complete API documentation with business context
- **Deploy**: Create production-ready APIs with proper security and monitoring
