# Custom Templates Feature

This document explains how the Custom Templates feature works in the Template Manager service, following the same pattern as Custom Features.

## Overview

The Custom Templates feature allows users to submit custom templates that go through an admin approval workflow before becoming available in the system. This follows the exact same pattern as the existing Custom Features implementation.

## Architecture

### Database Tables

1. **`custom_templates`** - Stores custom template submissions with admin approval workflow
2. **`templates`** - Mirrors approved custom templates (with `type = 'custom_<id>'`)

### Models

- **`CustomTemplate`** - Handles custom template CRUD operations and admin workflow
- **`Template`** - Standard template model (mirrors approved custom templates)

### Routes

- **`/api/custom-templates`** - Public endpoints for creating/managing custom templates
- **`/api/admin/templates/*`** - Admin endpoints for reviewing custom templates

## How It Works

### 1. Template Submission
```
User submits custom template → CustomTemplate.create() → Admin notification → Mirror to templates table
```

### 2. Admin Review Process
```
Admin reviews → Updates status → If approved: activates mirrored template → If rejected: keeps inactive
```

### 3. Template Mirroring
- Custom templates are mirrored into the `templates` table with `type = 'custom_<id>'`
- This allows them to be used by existing template endpoints
- The mirrored template starts with `is_active = false` until approved

## API Endpoints

### Public Custom Template Endpoints

#### POST `/api/custom-templates`
Create a new custom template.

**Required fields:**
- `type` - Template type identifier
- `title` - Template title
- `category` - Template category
- `complexity` - 'low', 'medium', or 'high'

**Optional fields:**
- `description` - Template description
- `icon` - Icon identifier
- `gradient` - CSS gradient
- `border` - Border styling
- `text` - Primary text
- `subtext` - Secondary text
- `business_rules` - JSON business rules
- `technical_requirements` - JSON technical requirements
- `created_by_user_session` - User session identifier

**Response:**
```json
{
  "success": true,
  "data": {
    "id": "uuid",
    "type": "custom_type",
    "title": "Custom Template",
    "status": "pending",
    "approved": false
  },
  "message": "Custom template 'Custom Template' created successfully and submitted for admin review"
}
```

#### GET `/api/custom-templates`
Get all custom templates with pagination.

**Query parameters:**
- `limit` - Number of templates to return (default: 100)
- `offset` - Number of templates to skip (default: 0)

#### GET `/api/custom-templates/search`
Search custom templates by title, description, or category.

**Query parameters:**
- `q` - Search term (required)
- `limit` - Maximum results (default: 20)

#### GET `/api/custom-templates/:id`
Get a specific custom template by ID.

#### PUT `/api/custom-templates/:id`
Update a custom template.

#### DELETE `/api/custom-templates/:id`
Delete a custom template.

#### GET `/api/custom-templates/status/:status`
Get custom templates by status.

**Valid statuses:** `pending`, `approved`, `rejected`, `duplicate`

#### GET `/api/custom-templates/stats`
Get custom template statistics.

### Admin Endpoints

#### GET `/api/admin/templates/pending`
Get pending templates for admin review.

#### GET `/api/admin/templates/status/:status`
Get templates by status (admin view).

#### POST `/api/admin/templates/:id/review`
Review a custom template.

**Request body:**
```json
{
  "status": "approved|rejected|duplicate",
  "admin_notes": "Optional admin notes",
  "canonical_template_id": "UUID of similar template (if duplicate)"
}
```

#### GET `/api/admin/templates/stats`
Get custom template statistics for admin dashboard.

### Template Merging Endpoints

#### GET `/api/templates/merged`
Get all templates (default + approved custom) grouped by category.

This endpoint merges default templates with approved custom templates, providing a unified view.

## Database Schema

### `custom_templates` Table

```sql
CREATE TABLE custom_templates (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  type VARCHAR(100) NOT NULL,
  title VARCHAR(200) NOT NULL,
  description TEXT,
  icon VARCHAR(50),
  category VARCHAR(100) NOT NULL,
  gradient VARCHAR(100),
  border VARCHAR(100),
  text VARCHAR(100),
  subtext VARCHAR(100),
  complexity VARCHAR(50) NOT NULL CHECK (complexity IN ('low', 'medium', 'high')),
  business_rules JSONB,
  technical_requirements JSONB,
  approved BOOLEAN DEFAULT false,
  usage_count INTEGER DEFAULT 1,
  created_by_user_session VARCHAR(100),
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW(),
  -- Admin approval workflow fields
  status VARCHAR(50) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected', 'duplicate')),
  admin_notes TEXT,
  admin_reviewed_at TIMESTAMP,
  admin_reviewed_by VARCHAR(100),
  canonical_template_id UUID REFERENCES templates(id) ON DELETE SET NULL,
  similarity_score FLOAT CHECK (similarity_score >= 0 AND similarity_score <= 1)
);
```

## Admin Workflow

### 1. Template Submission
1. User creates custom template via `/api/custom-templates`
2. Template is saved with `status = 'pending'`
3. Admin notification is created
4. Template is mirrored to `templates` table with `is_active = false`

### 2. Admin Review
1. Admin views pending templates via `/api/admin/templates/pending`
2. Admin reviews template and sets status:
   - **Approved**: Template becomes active, mirrored template is activated
   - **Rejected**: Template remains inactive
   - **Duplicate**: Template marked as duplicate with reference to canonical template

### 3. Template Activation
- Approved templates have their mirrored version activated (`is_active = true`)
- Rejected/duplicate templates remain inactive
- All templates are accessible via the merged endpoints

## Usage Examples

### Creating a Custom Template

```javascript
const response = await fetch('/api/custom-templates', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    type: 'ecommerce_custom',
    title: 'Custom E-commerce Template',
    description: 'A specialized e-commerce template for fashion retailers',
    category: 'E-commerce',
    complexity: 'medium',
    business_rules: { payment_methods: ['stripe', 'paypal'] },
    technical_requirements: { framework: 'react', backend: 'nodejs' }
  })
});
```

### Admin Review

```javascript
const reviewResponse = await fetch('/api/admin/templates/uuid/review', {
  method: 'POST',
  headers: { 
    'Content-Type': 'application/json',
    'Authorization': 'Bearer admin-jwt-token'
  },
  body: JSON.stringify({
    status: 'approved',
    admin_notes: 'Great template design, approved for production use'
  })
});
```

### Getting Merged Templates

```javascript
const mergedTemplates = await fetch('/api/templates/merged');
// Returns default + approved custom templates grouped by category
```

## Migration

To add custom templates support to an existing database:

1. Run the migration: `node src/migrations/migrate.js`
2. The migration will create the `custom_templates` table
3. Existing templates and features remain unchanged
4. New custom templates will be stored separately and mirrored

## Benefits

1. **Non-disruptive**: Existing templates and features remain unchanged
2. **Consistent Pattern**: Follows the same workflow as custom features
3. **Admin Control**: All custom templates go through approval process
4. **Unified Access**: Approved custom templates are accessible via existing endpoints
5. **Audit Trail**: Full tracking of submission, review, and approval process

## Security Considerations

1. **Admin Authentication**: All admin endpoints require JWT with admin role
2. **Input Validation**: All user inputs are validated and sanitized
3. **Status Checks**: Only approved templates become active
4. **Session Tracking**: User sessions are tracked for audit purposes

## Future Enhancements

1. **Template Similarity Detection**: Automatic duplicate detection
2. **Bulk Operations**: Approve/reject multiple templates at once
3. **Template Versioning**: Track changes and versions
4. **Template Analytics**: Usage statistics and performance metrics
5. **Template Categories**: Dynamic category management
