/**
 * GSB Schema Management Documentation
 * ==============================
 * 
 * This file provides detailed documentation for GSB Schema Management tools,
 * including entity definition operations, property management, and relationship handling.
 */

/**
 * Returns documentation for the getCommonPropertyDefs operation
 */
export function getCommonPropertyDefsDocumentation(): string {
    return `
# Get Common Property Definitions

Retrieves the list of common property definitions that can be used when creating entity properties.

## Request Format

\`\`\`typescript
getCommonPropertyDefs(
    token: string,          // Authentication token
    tenantCode?: string     // Optional tenant code
): Promise<{
    success: boolean,
    data?: Record<string, any>,
    error?: string
}>
\`\`\`

## Response Format

\`\`\`json
{
    "success": boolean,
    "data": {
        // Dictionary of property definitions with their IDs as keys
    },
    "error": "string"      // Present only if success is false
}
\`\`\`

## Common Property Definition Types

| Type | Definition ID | Description |
|------|--------------|-------------|
| ID | 5c0aa76f-9c32-4e7e-a4bc-b56e93877883 | Unique identifier |
| String | c6c34bf3-f51b-4e69-a689-b09847be74b9 | Text string |
| Number | 35efcf9c-fff0-44d4-8972-73a9a32b93fa | Numeric value |
| Boolean | 7868afdf-2709-45be-87e3-87de8d35f30f | True/false value |
| DateTime | 12e647e0-ebd2-4ec2-a4e3-82c1dfe07da2 | Date and time |
| Reference | 924acba8-58c5-4881-940d-472ec01eba5f | Entity reference |
| Enum | 7bf08f4f-7de0-469e-bbfb-f4c43762f4d7 | Enumerated value |
| RichText | e07f578e-2705-49c1-b97f-3ca5963c67c0 | Rich text content |
| Email | df7ce94b-d59c-4b67-8519-aa4c98ab477c | Email address |
| Password | 7291fbc2-a7cf-4713-a876-0cff085cc035 | Password field |

## Example

\`\`\`typescript
const result = await getCommonPropertyDefs("your-auth-token");
// Access a specific property definition
const stringType = result.data["c6c34bf3-f51b-4e69-a689-b09847be74b9"];
\`\`\`
`;
}

/**
 * Returns documentation for the createEntityDef operation
 */
export function createEntityDefDocumentation(): string {
    return `
# Create Entity Definition

Creates a new entity definition (data table) with the specified schema.

## Request Format

\`\`\`typescript
createEntityDef(
    entityDef: GsbEntityDef,  // Entity definition object
    token: string,           // Authentication token
    tenantCode?: string      // Optional tenant code
): Promise<{
    success: boolean,
    data?: string,           // ID of the created entity definition
    error?: string
}>
\`\`\`

## GsbEntityDef Structure

\`\`\`typescript
interface GsbEntityDef {
  id?: string;                        // Unique identifier (auto-generated if not provided)
  name?: string;                      // Entity name (must be unique)
  title?: string;                     // Display title
  description?: string;               // Description
  dbTableName?: string;               // Database table name
  publicAccess?: boolean;             // Whether entity is publicly accessible
  activityLogLevel?: ActivityLogLevel; // Level of activity logging
  properties?: GsbProperty[];         // Array of properties (columns)
  isActive?: boolean;                 // Whether entity is active
  isDeleted?: boolean;                // Whether entity is deleted
  permissions?: GsbPermission[];      // Entity permissions
  workflowTriggers?: GsbWorkflowTrigger[]; // Associated workflow triggers
}
\`\`\`

## Default Properties

When creating a new entity definition, these properties are automatically added:

1. \`id\` - Primary key (UUID), Required
2. \`title\` - Display title
3. \`createdBy\` - User who created the record
4. \`lastUpdatedBy\` - User who last updated the record
5. \`createDate\` - Creation timestamp
6. \`lastUpdateDate\` - Last update timestamp

## Response Format

\`\`\`json
{
    "success": boolean,
    "data": "string",       // ID of the created entity definition
    "error": "string"      // Present only if success is false
}
\`\`\`

## Example

\`\`\`typescript
const entityDef = {
  name: "Customer",
  title: "Customer Information",
  description: "Stores customer data",
  properties: [
    {
      name: "email",
      title: "Email Address",
      description: "Customer email",
      definition_id: "df7ce94b-d59c-4b67-8519-aa4c98ab477c", // Email type
      isRequired: true,
      isUnique: true,
      isSearchable: true,
      orderNumber: 10
    },
    {
      name: "phoneNumber",
      title: "Phone Number",
      description: "Customer phone number",
      definition_id: "c6c34bf3-f51b-4e69-a689-b09847be74b9", // String type
      isSearchable: true,
      orderNumber: 20
    }
  ]
};

const result = await createEntityDef(entityDef, "your-auth-token");
\`\`\`
`;
}

/**
 * Returns documentation for the updateEntityDef operation
 */
export function updateEntityDefDocumentation(): string {
    return `
# Update Entity Definition

Updates an existing entity definition with new schema information.

## Request Format

\`\`\`typescript
updateEntityDef(
    entityDef: GsbEntityDef,  // Entity definition object with ID
    token: string,           // Authentication token
    tenantCode?: string      // Optional tenant code
): Promise<{
    success: boolean,
    data?: boolean,          // Success status
    error?: string
}>
\`\`\`

## Important Notes

- The \`id\` field in the entityDef object is required for updates
- Only the fields provided in the entityDef object will be updated
- To update properties, use the dedicated property management methods

## Response Format

\`\`\`json
{
    "success": boolean,
    "data": boolean,        // True if update was successful
    "error": "string"      // Present only if success is false
}
\`\`\`

## Example

\`\`\`typescript
const entityDef = {
  id: "12345",             // Required for update
  title: "Updated Customer Information",
  description: "Updated customer data storage"
};

const result = await updateEntityDef(entityDef, "your-auth-token");
\`\`\`

## Schema Evolution

When updating entity definitions:

1. Changing \`name\` or \`dbTableName\` will rename the database table
2. Setting \`isActive: false\` will disable operations on the entity
3. Updating \`publicAccess\` will change security settings
4. Modifying \`activityLogLevel\` will change audit trail behavior

Be careful when updating entity definitions in production systems, as some changes may affect existing data or application behavior.
`;
}

/**
 * Returns documentation for the addProperty operation
 */
export function addPropertyDocumentation(): string {
    return `
# Add Property

Adds a new property (column) to an existing entity definition.

## Request Format

\`\`\`typescript
addProperty(
    entityDefId: string,     // ID of the entity definition to modify
    property: GsbProperty,   // Property definition to add
    token: string,           // Authentication token
    tenantCode?: string      // Optional tenant code
): Promise<{
    success: boolean,
    data?: boolean,          // Success status
    error?: string
}>
\`\`\`

## GsbProperty Structure

\`\`\`typescript
interface GsbProperty {
  id?: string;                     // Unique identifier (auto-generated if not provided)
  name?: string;                   // Property name (must be unique within entity)
  title?: string;                  // Display title
  description?: string;            // Description
  definition_id?: string;          // Reference to property definition (data type)
  orderNumber?: number;            // Display order
  isRequired?: boolean;            // Whether property is required
  isSearchable?: boolean;          // Whether property is searchable
  isUnique?: boolean;              // Whether property must have unique values
  isPrimaryKey?: boolean;          // Whether property is a primary key
  isIndexed?: boolean;             // Whether property is indexed
  maxLength?: number;              // Maximum length (for strings)
  defaultValue?: string;           // Default value
  
  // Reference properties
  refEntDef_id?: string;           // Referenced entity definition ID
  refEntPropName?: string;         // Property name in referenced entity
  refType?: RefType;               // Reference type (OneToOne, OneToMany, etc.)
  
  // UI control properties
  formModes?: number;              // Form modes where property is visible
  listScreens?: number;            // List screens where property is visible
  
  // Additional properties
  enum_id?: string;                // Enum ID (for enum properties)
  isMultiLingual?: boolean;        // Whether property supports multiple languages
  isEncrypted?: boolean;           // Whether property value is encrypted
  regex?: string;                  // Validation regex pattern
}
\`\`\`

## Reference Types

When creating reference properties, use one of these reference types:

\`\`\`typescript
enum RefType {
  OneToOne = 1,
  OneToMany = 2,
  ManyToOne = 3,
  ManyToMany = 4
}
\`\`\`

## Response Format

\`\`\`json
{
    "success": boolean,
    "data": boolean,        // True if property was added successfully
    "error": "string"      // Present only if success is false
}
\`\`\`

## Example: Adding a Simple Property

\`\`\`typescript
const property = {
  name: "address",
  title: "Address",
  description: "Customer address",
  definition_id: "c6c34bf3-f51b-4e69-a689-b09847be74b9", // String type
  isSearchable: true,
  orderNumber: 30
};

const result = await addProperty("entity-id", property, "your-auth-token");
\`\`\`

## Example: Adding a Reference Property

\`\`\`typescript
const property = {
  name: "category",
  title: "Category",
  description: "Product category",
  definition_id: "924acba8-58c5-4881-940d-472ec01eba5f", // Reference type
  refEntDef_id: "category-entity-id",
  refEntPropName: "products", // Creates a 'products' property in Category entity
  refType: 3, // ManyToOne
  orderNumber: 40
};

const result = await addProperty("product-entity-id", property, "your-auth-token");
\`\`\`

## Auto-Mirror Properties

When adding a reference property with \`refEntPropName\` specified:

1. GSB automatically creates the mirror property in the referenced entity
2. The relationship is managed bidirectionally
3. For ManyToMany relationships, a mapping table is created automatically
`;
}

/**
 * Returns documentation for the removeProperty operation
 */
export function removePropertyDocumentation(): string {
    return `
# Remove Property

Removes a property (column) from an existing entity definition.

## Request Format

\`\`\`typescript
removeProperty(
    entityDefId: string,     // ID of the entity definition to modify
    propertyName: string,    // Name of the property to remove
    token: string,           // Authentication token
    tenantCode?: string      // Optional tenant code
): Promise<{
    success: boolean,
    data?: boolean,          // Success status
    error?: string
}>
\`\`\`

## Response Format

\`\`\`json
{
    "success": boolean,
    "data": boolean,        // True if property was removed successfully
    "error": "string"      // Present only if success is false
}
\`\`\`

## Example

\`\`\`typescript
const result = await removeProperty("entity-id", "address", "your-auth-token");
\`\`\`

## Important Notes

1. **Data Loss Warning**: Removing a property will delete all data stored in that column
2. **Default Properties**: Some default properties (like \`id\`) cannot be removed
3. **Reference Properties**: When removing a reference property:
   - The mirror property in the referenced entity is also removed
   - For ManyToMany relationships, the mapping table may be dropped
4. **Dependent Components**: Check for UI components or business logic that depend on the property before removal
`;
}

/**
 * Returns documentation for the updateProperty operation
 */
export function updatePropertyDocumentation(): string {
    return `
# Update Property

Updates an existing property in an entity definition.

## Request Format

\`\`\`typescript
updateProperty({
    entityDefId: string,     // ID of the entity definition to modify
    propertyName: string,    // Name of the property to update
    property: GsbProperty,   // Updated property definition
    token?: string,          // Authentication token
    tenantCode?: string      // Optional tenant code
}): Promise<{
    success: boolean,
    data?: boolean,          // Success status
    error?: string
}>
\`\`\`

## Important Notes

- The \`name\` field in the property object identifies which property to update
- Only the fields provided in the property object will be updated
- Some property attributes cannot be changed after creation (e.g., \`definition_id\`)

## Response Format

\`\`\`json
{
    "success": boolean,
    "data": boolean,        // True if property was updated successfully
    "error": "string"      // Present only if success is false
}
\`\`\`

## Example

\`\`\`typescript
const property = {
  name: "address",          // Identifies which property to update
  title: "Updated Address",
  description: "Updated customer address",
  isRequired: true,
  maxLength: 200
};

const result = await updateProperty({
  entityDefId: "entity-id", 
  propertyName: "address",
  property: property, 
  token: "your-auth-token"
});
\`\`\`

## Safe vs. Unsafe Updates

### Safe Updates (No data loss risk)
- \`title\`
- \`description\`
- \`orderNumber\`
- \`isSearchable\`
- \`isIndexed\`
- \`formModes\`
- \`listScreens\`

### Potentially Unsafe Updates (May affect data)
- \`isRequired\` (if changing from false to true)
- \`isUnique\` (if changing from false to true)
- \`maxLength\` (if decreasing)
- \`regex\` (if adding or making more restrictive)

### Unsafe Updates (May require data migration)
- \`definition_id\` (changing data type)
- \`refEntDef_id\` (changing referenced entity)
- \`refType\` (changing relationship type)
`;
}

/**
 * Returns documentation for the getEntityDef operation
 */
export function getEntityDefDocumentation(): string {
    return `
# Get Entity Definition

Retrieves an entity definition by its ID.

## Request Format

\`\`\`typescript
getEntityDef(
    entityDefId: string,     // ID of the entity definition to retrieve
    token: string,           // Authentication token
    tenantCode?: string      // Optional tenant code
): Promise<{
    success: boolean,
    data?: {
        entityDef: GsbEntityDef     // Entity definition object
    },
    error?: string
}>
\`\`\`

## Response Format

\`\`\`json
{
    "success": boolean,
    "data": {
        "entityDef": {
            "id": "string",
            "name": "string",
            "title": "string",
            "description": "string",
            "dbTableName": "string",
            "publicAccess": boolean,
            "activityLogLevel": number,
            "properties": [
                // Array of GsbProperty objects
            ],
            "isActive": boolean,
            "isDeleted": boolean,
            "createDate": "string",
            "lastUpdateDate": "string",
            "createdBy_id": "string",
            "lastUpdatedBy_id": "string",
            "permissions": [
                // Array of permission objects
            ],
            "workflowTriggers": [
                // Array of workflow trigger objects
            ]
        }
    },
    "error": "string"      // Present only if success is false
}
\`\`\`

## Example

\`\`\`typescript
const result = await getEntityDef("entity-id", "your-auth-token");
const entityDef = result.data.entityDef;
\`\`\`

## Using Entity Definition Data

The retrieved entity definition contains complete schema information that can be used for:

1. **Metadata Exploration**: Understanding the structure of the entity
2. **Dynamic UI Generation**: Building forms or tables based on properties
3. **Schema Modification**: Making changes to the entity definition
4. **Relationship Analysis**: Examining references between entities
`;
}

/**
 * Returns documentation for the queryEntityDefs operation
 */
export function queryEntityDefsDocumentation(): string {
    return `
# Query Entity Definitions

Retrieves a paginated list of entity definitions.

## Request Format

\`\`\`typescript
queryEntityDefs(
    page: number,           // Page number (1-based)
    pageSize: number,       // Number of items per page
    token: string,          // Authentication token
    tenantCode?: string     // Optional tenant code
): Promise<{
    success: boolean,
    data?: {
        entityDefs: GsbEntityDef[],  // Array of entity definitions
        totalCount: number           // Total number of entity definitions
    },
    error?: string
}>
\`\`\`

## Response Format

\`\`\`json
{
    "success": boolean,
    "data": {
        "entityDefs": [
            // Array of entity definition objects
        ],
        "totalCount": number
    },
    "error": "string"      // Present only if success is false
}
\`\`\`

## Example

\`\`\`typescript
// Get the first page with 10 entity definitions per page
const result = await queryEntityDefs(1, 10, "your-auth-token");

// Access the entity definitions and total count
const { entityDefs, totalCount } = result.data;

// Calculate total pages
const totalPages = Math.ceil(totalCount / 10);
\`\`\`

## Pagination

- Page numbers start at 1
- If there are no results for the specified page, an empty array is returned
- The \`totalCount\` field indicates the total number of entity definitions available

## Use Cases

1. **Schema Browser**: Building a UI to explore available data tables
2. **Data Dictionary**: Creating documentation of the data model
3. **Dependency Analysis**: Finding relationships between entities
4. **Schema Governance**: Monitoring entity definitions for compliance
`;
}

/**
 * Returns documentation for the schema management tools
 * @param methodName {string=} Optional method name to get specific documentation
 * @return {string} markdown documentation for the specified method or complete API
 */
export function getDefDocs(methodName?: string): string {
    // If a method name is provided, return specific documentation
    if (methodName) {
        switch (methodName.toLowerCase()) {
            case 'getcommonpropertydefs':
                return getCommonPropertyDefsDocumentation();
            case 'createentitydef':
                return createEntityDefDocumentation();
            case 'updateentitydef':
                return updateEntityDefDocumentation();
            case 'addproperty':
                return addPropertyDocumentation();
            case 'removeproperty':
                return removePropertyDocumentation();
            case 'updateproperty':
                return updatePropertyDocumentation();
            case 'getentitydef':
                return getEntityDefDocumentation();
            case 'queryentitydefs':
                return queryEntityDefsDocumentation();
            default:
                return `Method '${methodName}' not found. Available methods:\n\n` +
                       `- getCommonPropertyDefs\n- createEntityDef\n- updateEntityDef\n` +
                       `- addProperty\n- removeProperty\n- updateProperty\n` +
                       `- getEntityDef\n- queryEntityDefs`;
        }
    }

    // Return complete documentation if no method specified
    return `
# GSB Schema Management API Documentation

## Overview

The GSB Schema Management API provides a comprehensive set of operations for managing entity definitions (data tables) in your GSB applications.
All operations require authentication via a token, and optionally accept a tenant code.

## Key Concepts

1. **Entity Definition**: Represents a data table in the database
2. **Property**: Represents a column in a data table
3. **Property Definition**: Defines the data type and behavior of properties
4. **References**: Define relationships between entities

## Available Documentation

To get detailed documentation for a specific method, call getDefDocs with the method name as parameter:
\`getDefDocs("methodName")\`

### Entity Definition Management

- **getCommonPropertyDefs**: Get available property data types
- **createEntityDef**: Create a new data table
- **updateEntityDef**: Update an existing data table
- **getEntityDef**: Get a data table by ID
- **queryEntityDefs**: Get paginated list of data tables

### Property Management

- **addProperty**: Add a column to a data table
- **removeProperty**: Remove a column from a data table
- **updateProperty**: Update a column in a data table

## Best Practices

1. **Entity Definition Naming**
   - Use PascalCase for entity names
   - Use singular nouns
   - Be descriptive but concise
   - Avoid special characters
   - Start with a letter

2. **Property Naming**
   - Use camelCase for property names
   - Be descriptive
   - Use consistent naming patterns
   - Prefix boolean properties with 'is' or 'has'

3. **Schema Design**
   - Normalize appropriately
   - Use references instead of duplicating data
   - Add appropriate indexes
   - Set searchable fields
   - Define required fields
   - Set appropriate field lengths`;
}

// Export the main documentation function
export default getDefDocs; 