"use strict";
/**
 * API Reference Documentation Template
 * Auto-generates API documentation from models, relationships, and endpoints
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiReferenceTemplate = void 0;
const base_template_1 = require("./base-template");
class ApiReferenceTemplate extends base_template_1.DocumentationTemplate {
    canHandle(intent) {
        return intent.type === 'api_reference';
    }
    generate(context) {
        const { workflow, extendedWorkflow } = context;
        let content = `# API Reference\n\n`;
        if (workflow.workflow.description) {
            content += `${workflow.workflow.description}\n\n`;
        }
        // Base URL section
        content += this.generateBaseUrl(context);
        // Authentication section
        if (extendedWorkflow?.auth?.enabled) {
            content += this.generateAuthentication(context);
        }
        // Models/Resources section
        if (extendedWorkflow?.models) {
            content += this.generateModels(context);
        }
        // Endpoints section
        if (extendedWorkflow?.api?.endpoints) {
            content += this.generateEndpoints(context);
        }
        // Relationships section
        if (extendedWorkflow?.relationships) {
            content += this.generateRelationships(context);
        }
        // Error responses
        content += this.generateErrorResponses(context);
        content += this.generateFooter(context);
        return content;
    }
    generateBaseUrl(context) {
        const { extendedWorkflow } = context;
        const basePath = extendedWorkflow?.api?.base_path || '/api';
        let content = `## Base URL\n\n`;
        content += '```\n';
        content += `http://localhost:3001${basePath}\n`;
        content += '```\n\n';
        content += `All endpoints are relative to this base URL.\n\n`;
        return content;
    }
    generateAuthentication(context) {
        const { extendedWorkflow } = context;
        const provider = extendedWorkflow?.auth?.provider || 'authentication';
        let content = `## Authentication\n\n`;
        content += `This API uses **${this.capitalize(provider)}** for authentication.\n\n`;
        if (provider === 'clerk') {
            content += `### Using Clerk\n\n`;
            content += `Include your session token in requests:\n\n`;
            content += '```http\n';
            content += `Authorization: Bearer <clerk_session_token>\n`;
            content += '```\n\n';
            content += `**Frontend Example:**\n`;
            content += '```typescript\n';
            content += `import { useAuth } from '@clerk/clerk-react';\n\n`;
            content += `const { getToken } = useAuth();\n`;
            content += `const token = await getToken();\n\n`;
            content += `fetch('/api/users', {\n`;
            content += `  headers: {\n`;
            content += `    'Authorization': \`Bearer \${token}\`\n`;
            content += `  }\n`;
            content += `});\n`;
            content += '```\n\n';
        }
        else if (provider === 'local') {
            content += `### Using JWT\n\n`;
            content += `Include your JWT token in requests:\n\n`;
            content += '```http\n';
            content += `Authorization: Bearer <jwt_token>\n`;
            content += '```\n\n';
        }
        return content;
    }
    generateModels(context) {
        const { extendedWorkflow } = context;
        const models = extendedWorkflow?.models || {};
        let content = `## Data Models\n\n`;
        content += `The following data models are available in this API:\n\n`;
        for (const [modelName, model] of Object.entries(models)) {
            const modelData = model;
            content += `### ${modelName}\n\n`;
            if (modelData.description) {
                content += `${modelData.description}\n\n`;
            }
            content += `**Fields:**\n\n`;
            content += `| Field | Type | Required | Description |\n`;
            content += `|-------|------|----------|-------------|\n`;
            // Add ID field (always present)
            content += `| \`id\` | uuid | Yes | Unique identifier |\n`;
            // Add model fields
            for (const [fieldName, field] of Object.entries(modelData.fields)) {
                const fieldData = field;
                const required = fieldData.required ? 'Yes' : 'No';
                const description = fieldData.description || '';
                let typeInfo = fieldData.type;
                if (fieldData.type === 'enum' && fieldData.enum_values) {
                    typeInfo = `enum (${fieldData.enum_values.join(', ')})`;
                }
                if (fieldData.foreign_key) {
                    typeInfo += ` → ${fieldData.foreign_key}`;
                }
                content += `| \`${fieldName}\` | ${typeInfo} | ${required} | ${description} |\n`;
            }
            // Add timestamp fields if enabled
            if (modelData.timestamps !== false) {
                content += `| \`created_at\` | timestamp | Yes | Creation timestamp |\n`;
                content += `| \`updated_at\` | timestamp | Yes | Last update timestamp |\n`;
            }
            if (modelData.soft_delete) {
                content += `| \`deleted_at\` | timestamp | No | Soft delete timestamp |\n`;
            }
            content += '\n';
            // Add example JSON
            content += `**Example:**\n\n`;
            content += '```json\n';
            content += this.generateModelExample(modelName, model);
            content += '```\n\n';
        }
        return content;
    }
    generateModelExample(modelName, model) {
        const example = {
            id: 'uuid-example-123',
        };
        for (const [fieldName, field] of Object.entries(model.fields)) {
            example[fieldName] = this.getExampleValue(fieldName, field);
        }
        if (model.timestamps !== false) {
            example.created_at = '2024-01-15T10:30:00Z';
            example.updated_at = '2024-01-15T10:30:00Z';
        }
        return JSON.stringify(example, null, 2);
    }
    getExampleValue(fieldName, field) {
        switch (field.type) {
            case 'string':
                if (fieldName.includes('email'))
                    return 'user@example.com';
                if (fieldName.includes('name'))
                    return 'Example Name';
                if (fieldName.includes('url'))
                    return 'https://example.com';
                return 'example';
            case 'text':
                return 'Example text content';
            case 'integer':
                return 42;
            case 'decimal':
                return 99.99;
            case 'boolean':
                return true;
            case 'timestamp':
            case 'date':
                return '2024-01-15T10:30:00Z';
            case 'enum':
                return field.enum_values?.[0] || 'value';
            case 'json':
                return { key: 'value' };
            case 'array':
                return ['item1', 'item2'];
            case 'uuid':
                return 'uuid-example-123';
            default:
                return null;
        }
    }
    generateEndpoints(context) {
        const { extendedWorkflow } = context;
        const endpoints = extendedWorkflow?.api?.endpoints || [];
        let content = `## Endpoints\n\n`;
        // Group endpoints by resource
        const endpointsByResource = this.groupEndpointsByResource(endpoints);
        for (const [resource, resourceEndpoints] of Object.entries(endpointsByResource)) {
            content += `### ${resource}\n\n`;
            for (const endpoint of resourceEndpoints) {
                content += `#### ${endpoint.method} ${endpoint.path}\n\n`;
                if (endpoint.description) {
                    content += `${endpoint.description}\n\n`;
                }
                // Authentication requirements
                if (endpoint.auth === 'required') {
                    content += `🔒 **Authentication Required**\n\n`;
                    if (endpoint.roles && endpoint.roles.length > 0) {
                        content += `**Allowed Roles:** ${endpoint.roles.join(', ')}\n\n`;
                    }
                    if (endpoint.ownership?.enabled) {
                        content += `**Ownership Check:** ${endpoint.ownership.field || 'user_id'}\n\n`;
                    }
                }
                // Request
                content += `**Request:**\n\n`;
                content += '```http\n';
                content += `${endpoint.method} ${endpoint.path}\n`;
                content += `Content-Type: application/json\n`;
                if (endpoint.auth === 'required') {
                    content += `Authorization: Bearer <token>\n`;
                }
                content += '```\n\n';
                // Request body
                if (endpoint.body && extendedWorkflow?.models?.[endpoint.body]) {
                    content += `**Request Body:**\n\n`;
                    content += '```json\n';
                    const model = extendedWorkflow.models[endpoint.body];
                    content += this.generateModelExample(endpoint.body, model);
                    content += '```\n\n';
                }
                // Response
                content += `**Response:**\n\n`;
                content += '```json\n';
                if (endpoint.response && extendedWorkflow?.models?.[endpoint.response]) {
                    const model = extendedWorkflow.models[endpoint.response];
                    content += this.generateModelExample(endpoint.response, model);
                }
                else {
                    content += `{\n  "success": true,\n  "data": {}\n}\n`;
                }
                content += '```\n\n';
            }
        }
        return content;
    }
    groupEndpointsByResource(endpoints) {
        const groups = {};
        for (const endpoint of endpoints) {
            // Extract resource from path (e.g., /users/:id -> Users)
            const pathParts = endpoint.path.split('/').filter((p) => p && !p.startsWith(':'));
            const resource = pathParts[0] ? this.capitalize(pathParts[0]) : 'General';
            if (!groups[resource]) {
                groups[resource] = [];
            }
            groups[resource].push(endpoint);
        }
        return groups;
    }
    generateRelationships(context) {
        const { extendedWorkflow } = context;
        const relationships = extendedWorkflow?.relationships || [];
        if (relationships.length === 0) {
            return '';
        }
        let content = `## Relationships\n\n`;
        content += `The following relationships exist between models:\n\n`;
        for (const rel of relationships) {
            content += `### ${rel.from} → ${rel.to}\n\n`;
            content += `**Type:** ${rel.type.replace(/_/g, ' ')}\n\n`;
            if (rel.description) {
                content += `${rel.description}\n\n`;
            }
            // Show how to include related data
            if (rel.api_access?.queryable !== false) {
                content += `**Query Parameter:**\n`;
                content += '```http\n';
                content += `GET /api/${rel.from.toLowerCase()}?include=${rel.to.toLowerCase()}\n`;
                content += '```\n\n';
            }
        }
        return content;
    }
    generateErrorResponses(_context) {
        let content = `## Error Responses\n\n`;
        content += `The API uses standard HTTP status codes:\n\n`;
        content += `| Status Code | Meaning |\n`;
        content += `|-------------|----------|\n`;
        content += `| 200 | Success |\n`;
        content += `| 201 | Created |\n`;
        content += `| 400 | Bad Request - Invalid input |\n`;
        content += `| 401 | Unauthorized - Authentication required |\n`;
        content += `| 403 | Forbidden - Insufficient permissions |\n`;
        content += `| 404 | Not Found - Resource doesn't exist |\n`;
        content += `| 500 | Internal Server Error |\n\n`;
        content += `**Error Response Format:**\n\n`;
        content += '```json\n';
        content += `{\n`;
        content += `  "error": {\n`;
        content += `    "message": "Error description",\n`;
        content += `    "code": "ERROR_CODE",\n`;
        content += `    "details": {}\n`;
        content += `  }\n`;
        content += `}\n`;
        content += '```\n\n';
        return content;
    }
}
exports.ApiReferenceTemplate = ApiReferenceTemplate;
//# sourceMappingURL=api-reference-template.js.map