# Data Models Specification

## Entity Relationship Diagram

```
┌─────────────────────────────────────────────────────────────────┐
│                              User                               │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐  │
│  │     Role        │  │    Setting      │  │     Image       │  │
│  │  • id           │  │  • id           │  │  • id           │  │
│  │  • name         │  │  • key          │  │  • uuid         │  │
│  │  • timestamps   │  │  • value        │  │  • path         │  │
│  └─────────────────┘  │  • timestamps   │  │  • is_temp      │  │
│       │ 1           │  └─────────────────┘  │  • is_public    │  │
│       ▼              │      │ 1            │  • timestamps   │  │
│  ┌─────────────────┐  │      ▼             └─────────────────┘  │
│  │  • id           │  │  ┌─────────────────┐                    │
│  │  • name         │  │  │   ApiProvider   │                    │
│  │  • email        │  │  │  • id           │                    │
│  │  • password     │  │  │  • name         │                    │
│  │  • role_id      │  │  │  • api_url      │                    │
│  │  • timestamps   │  │  │  • username     │                    │
│  │  • 2FA fields   │  │  │  • password     │                    │
│  └─────────────────┘  │  │  • token        │                    │
│       │              │  │  • plugin       │                    │
│       ▼              │  │  • enabled      │                    │
│  ┌─────────────────┐  │  │  • timestamps  │                    │
│  │     Style       │◄─┘  └─────────────────┘                    │
│  │  • id           │       │ 1                                 │
│  │  • title        │       ▼                                 │
│  │  • prompt       │  ┌─────────────────┐                     │
│  │  • description  │  │   AiModel       │                     │
│  │  • preview_img  │  │  • id           │                     │
│  │  • parameters   │  │  • name         │                     │
│  │  • ai_model_id  │  │  • model_id     │                     │
│  │  • enabled      │  │  • model_type   │                     │
│  │  • sort_order   │  │  • api_provider │                     │
│  │  • timestamps   │  │  • parameters   │                     │
│  └─────────────────┘  │  • enabled      │                     │
│       │              │  • timestamps   │                     │
│       ▼              │  └─────────────────┘                     │
│  ┌─────────────────┐  │                                      │
│  │   Original      │◄┘                                      │
│  │    Image        │                                         │
│  └─────────────────┘                                         │
└─────────────────────────────────────────────────────────────────┘
```

## Model Specifications

### 1. User Model

**Purpose**: Represents authenticated users of the application

**Table**: `users`

**Attributes**:
```php
id: bigint unsigned auto_increment primary key
name: varchar(255)                    // User's display name
email: varchar(255) unique           // Unique email address
password: varchar(255)               // Hashed password
role_id: bigint unsigned nullable    // Foreign key to roles table
email_notifications_enabled: tinyint(1) default(1)  // Email notification preference
theme_preference: varchar(255) default('light')     // UI theme preference
locale: varchar(255) default('en')   // Language preference
two_factor_secret: text nullable     // 2FA secret key
two_factor_recovery_codes: text nullable  // 2FA backup codes
two_factor_confirmed_at: timestamp nullable  // 2FA confirmation timestamp
created_at: timestamp nullable
updated_at: timestamp nullable
```

**Relationships**:
- **BelongsTo**: Role (one user has one role)
- **HasMany**: Images (one user can have many images)

**Business Rules**:
- Email must be unique across all users
- Password must be hashed using secure algorithm
- Role determines permissions and access levels
- 2FA fields are optional but provide enhanced security

---

### 2. Role Model

**Purpose**: Defines user roles for access control

**Table**: `roles`

**Attributes**:
```php
id: bigint unsigned auto_increment primary key
name: varchar(255) unique           // Role name (e.g., 'admin', 'user')
created_at: timestamp nullable
updated_at: timestamp nullable
```

**Relationships**:
- **HasMany**: Users (one role can have many users)

**Business Rules**:
- Role names must be unique
- Predefined roles: 'admin', 'user'
- Used by Filament for access control

---

### 3. Image Model

**Purpose**: Stores metadata for uploaded and AI-generated images

**Table**: `images`

**Attributes**:
```php
id: bigint unsigned auto_increment primary key
uuid: char(36) unique nullable      // Unique identifier for tracking
path: varchar(255)                  // File path relative to storage disk
original_image_id: bigint unsigned nullable  // FK to original image (for styled images)
style_id: bigint unsigned nullable  // FK to applied style
is_temp: tinyint(1) default(0)      // True for temporary styled images
is_public: tinyint(1) default(1)    // True for publicly visible images
comfyui_prompt_id: varchar(255) nullable  // Tracking ID from ComfyUI
created_at: timestamp nullable
updated_at: timestamp nullable
```

**Relationships**:
- **BelongsTo**: Style (many images can use one style)
- **BelongsTo**: Original Image (self-referencing, styled images reference originals)
- **HasMany**: Styled Images (self-referencing, original images have many styled versions)

**Business Rules**:
- UUID is generated for tracking and external references
- Original images have `original_image_id` = null
- Styled images reference original via `original_image_id`
- Temporary images (`is_temp = true`) are pending user decision
- Public images (`is_public = true`) are visible to all users
- ComfyUI prompt ID tracks processing jobs

---

### 4. Style Model

**Purpose**: Defines AI artistic styles available for image transformation

**Table**: `styles`

**Attributes**:
```php
id: bigint unsigned auto_increment primary key
title: varchar(255)                 // Display name of the style
prompt: longtext                    // AI prompt describing the style
description: longtext               // Human-readable description
preview_image: varchar(255)         // Path to style preview image
parameters: json nullable           // Additional AI parameters (cast to array)
ai_model_id: bigint unsigned       // FK to associated AI model
enabled: tinyint(1) default(1)      // Whether style is active
sort_order: integer default(0)      // Display order in UI
created_at: timestamp nullable
updated_at: timestamp nullable
```

**Relationships**:
- **BelongsTo**: AiModel (many styles can use one AI model)
- **HasMany**: Images (one style can be applied to many images)

**Business Rules**:
- Only enabled styles are available to users
- Preview images help users choose appropriate styles
- Parameters are JSON and merged with AI model parameters
- Sort order controls display sequence in style selector

---

### 5. AiModel Model

**Purpose**: Represents specific AI models available through providers

**Table**: `ai_models`

**Attributes**:
```php
id: bigint unsigned auto_increment primary key
name: varchar(255)                  // Human-readable model name
model_id: varchar(255)              // Identifier used by AI service
model_type: varchar(255) nullable   // Type/category (e.g., 'Stable Diffusion')
parameters: json nullable           // Default parameters (cast to array)
api_provider_id: bigint unsigned nullable  // FK to primary API provider
enabled: tinyint(1) default(1)      // Whether model is active
created_at: timestamp nullable
updated_at: timestamp nullable
```

**Relationships**:
- **BelongsTo**: ApiProvider (many models can use one provider)
- **HasMany**: Styles (one model can have many styles)

**Business Rules**:
- Model ID must match identifier expected by AI service
- Only enabled models are available for new styles
- Parameters provide defaults, merged with style parameters
- Primary API provider handles communication for this model

---

### 6. ApiProvider Model

**Purpose**: Configures connections to external AI services

**Table**: `api_providers`

**Attributes**:
```php
id: bigint unsigned auto_increment primary key
name: varchar(255)                  // Provider name (e.g., 'ComfyUI Production')
api_url: varchar(255)               // Base URL of AI service
username: varchar(255) nullable     // Authentication username
password: varchar(255) nullable     // Authentication password
token: varchar(255) nullable        // API token/key
plugin: varchar(255)                // Plugin identifier (e.g., 'comfyui', 'runwareai')
enabled: tinyint(1) default(1)      // Whether provider is active
created_at: timestamp nullable
updated_at: timestamp nullable
```

**Relationships**:
- **HasMany**: AiModels (one provider can serve many models)
- **HasMany**: Styles (indirectly through AI models)

**Business Rules**:
- Plugin field determines which adapter to use
- Only enabled providers are available for processing
- Authentication credentials are encrypted/stored securely
- API URL must be valid and accessible

---

### 7. Setting Model

**Purpose**: Stores application-wide configuration settings

**Table**: `settings`

**Attributes**:
```php
id: bigint unsigned auto_increment primary key
key: varchar(255) unique            // Setting identifier
value: longtext nullable            // Setting value (can be JSON)
created_at: timestamp nullable
updated_at: timestamp nullable
```

**Relationships**: None (standalone configuration storage)

**Business Rules**:
- Keys must be unique across application
- Values can be simple strings or complex JSON
- Used for various configuration needs throughout app

## Data Integrity Constraints

### Foreign Key Relationships
- `users.role_id` → `roles.id` (nullable, defaults to user role)
- `images.original_image_id` → `images.id` (nullable, self-referencing)
- `images.style_id` → `styles.id` (nullable)
- `styles.ai_model_id` → `ai_models.id` (required)
- `ai_models.api_provider_id` → `api_providers.id` (nullable)

### Unique Constraints
- `users.email` (unique)
- `roles.name` (unique)
- `images.uuid` (unique, nullable)
- `settings.key` (unique)

### Check Constraints
- `images.is_temp` ∈ {0, 1}
- `images.is_public` ∈ {0, 1}
- `styles.enabled` ∈ {0, 1}
- `ai_models.enabled` ∈ {0, 1}
- `api_providers.enabled` ∈ {0, 1}

## Data Types & Casting

### Automatic Casting
- **Boolean Fields**: `enabled`, `is_temp`, `is_public` → boolean
- **JSON Fields**: `parameters` (in styles, ai_models) → array
- **Timestamps**: `created_at`, `updated_at` → datetime

### File Paths
- All image paths are relative to storage disk
- Preview images stored in `storage/app/public/style_previews/`
- Uploaded images stored in `storage/app/public/uploads/`

## Business Logic Implementation

### Image Path Resolution
- **Storage Disk**: Uses 'public' disk configuration
- **URL Generation**: `asset('storage/' . $image->path)`
- **File Location**: `public_path('storage/' . $image->path)`

### Parameter Merging
- **Style Parameters**: Override AI model parameters
- **Merge Strategy**: `array_replace_recursive($modelParams, $styleParams)`
- **Placeholder Replacement**: `__PROMPT__`, `__FILENAME__`, `__MODEL_ID__`

### UUID Usage
- **Image Tracking**: Unique identifier for external references
- **Generation**: Laravel's `HasUuids` trait or manual generation
- **Uniqueness**: Enforced by unique database constraint

## Data Access Patterns

### Common Queries
- **User Images**: `$user->images()` - all images for a user
- **Public Images**: `Image::where('is_public', true)`
- **Active Styles**: `Style::where('enabled', true)->with('aiModel')`
- **Enabled Models**: `AiModel::where('enabled', true)->with('primaryApiProvider')`

### Query Optimization
- **Eager Loading**: Styles load AI models and providers
- **Soft Deletes**: Not implemented (permanent deletion)
- **Indexing**: Consider indexes on frequently queried fields

## Migration Strategy

### Future Enhancements
- **Image Metadata**: EXIF data, dimensions, file size
- **Processing History**: Track all transformations applied to images
- **User Preferences**: Default styles, notification settings
- **Batch Operations**: Multiple image processing, bulk style application
- **Tagging System**: Categorize images with custom tags
- **Sharing Features**: Public galleries, social features

### Schema Evolution
- **Version Control**: Each model change requires migration
- **Backward Compatibility**: Maintain existing data integrity
- **Testing**: Validate schema changes against business rules