#![forbid(unsafe_code)]

//! OpenAPI 3.0 specification generator for the lifecycle API
//!
//! This module generates OpenAPI/Swagger documentation for the REST API
//! in JSON format (OpenAPI 3.0.0 specification).
//!
//! Features:
//! - Automatic generation of OpenAPI spec
//! - Full endpoint documentation
//! - Request/response schema definitions
//! - Authentication scheme documentation
//! - Server configuration
//!
//! # Example
//!
//! ```ignore
//! let spec = generate_openapi_spec();
//! let json = serde_json::to_string_pretty(&spec)?;
//! println!("{}", json);
//! ```

use serde_json::{json, Value};

/// Generate the complete OpenAPI 3.0 specification for the lifecycle API
pub fn generate_openapi_spec() -> Value {
    json!({
        "openapi": "3.0.0",
        "info": {
            "title": "Syntaxis Management API",
            "description": "REST API for managing syntaxis, phases, and workflows",
            "version": "1.0.0",
            "contact": {
                "name": "API Support",
                "url": "https://github.com/yourusername/syntaxis"
            },
            "license": {
                "name": "Apache 2.0",
                "url": "https://www.apache.org/licenses/LICENSE-2.0.html"
            }
        },
        "servers": [
            {
                "url": "http://localhost:3000",
                "description": "Development server",
                "variables": {
                    "protocol": {
                        "enum": ["http", "https"],
                        "default": "http"
                    },
                    "host": {
                        "default": "localhost"
                    },
                    "port": {
                        "default": "3000"
                    }
                }
            },
            {
                "url": "https://api.lifecycle.example.com",
                "description": "Production server"
            }
        ],
        "components": {
            "securitySchemes": {
                "BearerAuth": {
                    "type": "http",
                    "scheme": "bearer",
                    "bearerFormat": "JWT",
                    "description": "JWT Bearer token authentication"
                },
                "ApiKeyAuth": {
                    "type": "apiKey",
                    "in": "header",
                    "name": "Authorization",
                    "description": "API Key authentication with 'Bearer' prefix"
                }
            },
            "schemas": {
                "Project": {
                    "type": "object",
                    "required": ["id", "name"],
                    "properties": {
                        "id": {
                            "type": "string",
                            "format": "uuid",
                            "description": "Unique project identifier"
                        },
                        "name": {
                            "type": "string",
                            "description": "Project name"
                        },
                        "description": {
                            "type": "string",
                            "description": "Project description"
                        },
                        "project_type": {
                            "type": "string",
                            "enum": ["feature", "bugfix", "refactor", "documentation"],
                            "description": "Type of project"
                        },
                        "current_phase": {
                            "type": "string",
                            "description": "Current phase identifier"
                        },
                        "status": {
                            "type": "string",
                            "enum": ["created", "in_progress", "in_review", "completed", "archived"],
                            "description": "Project status"
                        },
                        "created_at": {
                            "type": "string",
                            "format": "date-time",
                            "description": "Creation timestamp"
                        },
                        "updated_at": {
                            "type": "string",
                            "format": "date-time",
                            "description": "Last update timestamp"
                        }
                    }
                },
                "ProjectStatus": {
                    "type": "object",
                    "properties": {
                        "project_id": {
                            "type": "string",
                            "format": "uuid"
                        },
                        "current_phase": {
                            "type": "string"
                        },
                        "phase_progress": {
                            "type": "number",
                            "minimum": 0.0,
                            "maximum": 100.0,
                            "description": "Phase completion percentage"
                        },
                        "checklist_items_completed": {
                            "type": "integer",
                            "description": "Number of completed checklist items"
                        },
                        "checklist_items_total": {
                            "type": "integer",
                            "description": "Total number of checklist items"
                        }
                    }
                },
                "ChecklistItem": {
                    "type": "object",
                    "required": ["id", "project_id", "title"],
                    "properties": {
                        "id": {
                            "type": "string",
                            "format": "uuid"
                        },
                        "project_id": {
                            "type": "string",
                            "format": "uuid"
                        },
                        "title": {
                            "type": "string"
                        },
                        "description": {
                            "type": "string"
                        },
                        "completed": {
                            "type": "boolean"
                        },
                        "priority": {
                            "type": "string",
                            "enum": ["low", "medium", "high"],
                            "description": "Priority level"
                        }
                    }
                },
                "SecurityAssessment": {
                    "type": "object",
                    "properties": {
                        "project_id": {
                            "type": "string",
                            "format": "uuid"
                        },
                        "risk_level": {
                            "type": "string",
                            "enum": ["low", "medium", "high", "critical"],
                            "description": "Overall security risk level"
                        },
                        "findings": {
                            "type": "array",
                            "description": "Security findings"
                        },
                        "assessment_date": {
                            "type": "string",
                            "format": "date-time"
                        }
                    }
                },
                "Error": {
                    "type": "object",
                    "required": ["error", "message"],
                    "properties": {
                        "error": {
                            "type": "string",
                            "description": "Error type"
                        },
                        "message": {
                            "type": "string",
                            "description": "Error message"
                        },
                        "details": {
                            "type": "object",
                            "description": "Additional error details"
                        }
                    }
                }
            }
        },
        "paths": {
            "/api/health": {
                "get": {
                    "tags": ["Health"],
                    "summary": "Health check endpoint",
                    "description": "Returns the health status of the API server",
                    "operationId": "health_check",
                    "responses": {
                        "200": {
                            "description": "Server is healthy",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {
                                            "status": {
                                                "type": "string",
                                                "example": "ok"
                                            },
                                            "uptime_seconds": {
                                                "type": "integer"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            "/api/projects": {
                "get": {
                    "tags": ["Projects"],
                    "summary": "List all projects",
                    "description": "Retrieve a list of all projects",
                    "operationId": "list_projects",
                    "security": [
                        {"BearerAuth": []},
                        {"ApiKeyAuth": []}
                    ],
                    "responses": {
                        "200": {
                            "description": "List of projects",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "array",
                                        "items": {
                                            "$ref": "#/components/schemas/Project"
                                        }
                                    }
                                }
                            }
                        },
                        "401": {
                            "description": "Unauthorized"
                        }
                    }
                },
                "post": {
                    "tags": ["Projects"],
                    "summary": "Create a new project",
                    "description": "Create a new project with the provided details",
                    "operationId": "create_project",
                    "security": [
                        {"BearerAuth": []},
                        {"ApiKeyAuth": []}
                    ],
                    "requestBody": {
                        "required": true,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "required": ["name", "project_type"],
                                    "properties": {
                                        "name": {
                                            "type": "string",
                                            "description": "Project name"
                                        },
                                        "description": {
                                            "type": "string",
                                            "description": "Project description"
                                        },
                                        "project_type": {
                                            "type": "string",
                                            "enum": ["feature", "bugfix", "refactor", "documentation"]
                                        }
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "201": {
                            "description": "Project created successfully",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/Project"
                                    }
                                }
                            }
                        },
                        "400": {
                            "description": "Invalid request"
                        },
                        "401": {
                            "description": "Unauthorized"
                        }
                    }
                }
            },
            "/api/projects/{id}": {
                "get": {
                    "tags": ["Projects"],
                    "summary": "Get project details",
                    "description": "Retrieve detailed information about a specific project",
                    "operationId": "get_project",
                    "security": [
                        {"BearerAuth": []},
                        {"ApiKeyAuth": []}
                    ],
                    "parameters": [
                        {
                            "name": "id",
                            "in": "path",
                            "required": true,
                            "schema": {
                                "type": "string",
                                "format": "uuid"
                            },
                            "description": "Project ID"
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "Project details",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/Project"
                                    }
                                }
                            }
                        },
                        "404": {
                            "description": "Project not found"
                        }
                    }
                },
                "put": {
                    "tags": ["Projects"],
                    "summary": "Update project",
                    "description": "Update an existing project",
                    "operationId": "update_project",
                    "security": [
                        {"BearerAuth": []},
                        {"ApiKeyAuth": []}
                    ],
                    "parameters": [
                        {
                            "name": "id",
                            "in": "path",
                            "required": true,
                            "schema": {
                                "type": "string",
                                "format": "uuid"
                            }
                        }
                    ],
                    "requestBody": {
                        "required": true,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "name": {
                                            "type": "string"
                                        },
                                        "description": {
                                            "type": "string"
                                        },
                                        "status": {
                                            "type": "string",
                                            "enum": ["created", "in_progress", "in_review", "completed", "archived"]
                                        }
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "200": {
                            "description": "Project updated successfully",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/Project"
                                    }
                                }
                            }
                        },
                        "404": {
                            "description": "Project not found"
                        }
                    }
                }
            },
            "/api/projects/{id}/status": {
                "get": {
                    "tags": ["Projects"],
                    "summary": "Get project status",
                    "description": "Retrieve the current status and progress of a project",
                    "operationId": "get_project_status",
                    "security": [
                        {"BearerAuth": []},
                        {"ApiKeyAuth": []}
                    ],
                    "parameters": [
                        {
                            "name": "id",
                            "in": "path",
                            "required": true,
                            "schema": {
                                "type": "string",
                                "format": "uuid"
                            }
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "Project status",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/ProjectStatus"
                                    }
                                }
                            }
                        }
                    }
                }
            },
            "/api/projects/{id}/checklists": {
                "get": {
                    "tags": ["Checklists"],
                    "summary": "Get checklist items",
                    "description": "Retrieve all checklist items for a project",
                    "operationId": "get_checklists",
                    "security": [
                        {"BearerAuth": []},
                        {"ApiKeyAuth": []}
                    ],
                    "parameters": [
                        {
                            "name": "id",
                            "in": "path",
                            "required": true,
                            "schema": {
                                "type": "string",
                                "format": "uuid"
                            }
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "List of checklist items",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "array",
                                        "items": {
                                            "$ref": "#/components/schemas/ChecklistItem"
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                "post": {
                    "tags": ["Checklists"],
                    "summary": "Add checklist item",
                    "description": "Add a new checklist item to a project",
                    "operationId": "add_checklist_item",
                    "security": [
                        {"BearerAuth": []},
                        {"ApiKeyAuth": []}
                    ],
                    "parameters": [
                        {
                            "name": "id",
                            "in": "path",
                            "required": true,
                            "schema": {
                                "type": "string",
                                "format": "uuid"
                            }
                        }
                    ],
                    "requestBody": {
                        "required": true,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "required": ["title"],
                                    "properties": {
                                        "title": {
                                            "type": "string"
                                        },
                                        "description": {
                                            "type": "string"
                                        },
                                        "priority": {
                                            "type": "string",
                                            "enum": ["low", "medium", "high"]
                                        }
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "201": {
                            "description": "Checklist item created",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/ChecklistItem"
                                    }
                                }
                            }
                        }
                    }
                }
            },
            "/api/projects/{id}/security": {
                "get": {
                    "tags": ["Security"],
                    "summary": "Get security assessment",
                    "description": "Retrieve the security assessment for a project",
                    "operationId": "get_security_assessment",
                    "security": [
                        {"BearerAuth": []},
                        {"ApiKeyAuth": []}
                    ],
                    "parameters": [
                        {
                            "name": "id",
                            "in": "path",
                            "required": true,
                            "schema": {
                                "type": "string",
                                "format": "uuid"
                            }
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "Security assessment",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "$ref": "#/components/schemas/SecurityAssessment"
                                    }
                                }
                            }
                        }
                    }
                }
            },
            "/metrics": {
                "get": {
                    "tags": ["Monitoring"],
                    "summary": "Prometheus metrics",
                    "description": "Export metrics in Prometheus format",
                    "operationId": "get_metrics",
                    "responses": {
                        "200": {
                            "description": "Prometheus metrics",
                            "content": {
                                "text/plain": {}
                            }
                        }
                    }
                }
            }
        },
        "tags": [
            {
                "name": "Health",
                "description": "Health check and status endpoints"
            },
            {
                "name": "Projects",
                "description": "Project management endpoints"
            },
            {
                "name": "Checklists",
                "description": "Checklist management endpoints"
            },
            {
                "name": "Security",
                "description": "Security assessment endpoints"
            },
            {
                "name": "Monitoring",
                "description": "Monitoring and metrics endpoints"
            }
        ]
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_openapi_spec_generation() {
        let spec = generate_openapi_spec();

        // Verify structure
        assert_eq!(spec["openapi"], "3.0.0");
        assert!(spec["info"]["title"].is_string());
        assert!(spec["servers"].is_array());
        assert!(spec["paths"].is_object());
        assert!(spec["components"]["schemas"].is_object());
    }

    #[test]
    fn test_openapi_has_health_endpoint() {
        let spec = generate_openapi_spec();
        assert!(spec["paths"]["/api/health"]["get"].is_object());
    }

    #[test]
    fn test_openapi_has_projects_endpoints() {
        let spec = generate_openapi_spec();
        assert!(spec["paths"]["/api/projects"]["get"].is_object());
        assert!(spec["paths"]["/api/projects"]["post"].is_object());
        assert!(spec["paths"]["/api/projects/{id}"]["get"].is_object());
        assert!(spec["paths"]["/api/projects/{id}"]["put"].is_object());
    }

    #[test]
    fn test_openapi_has_schemas() {
        let spec = generate_openapi_spec();
        assert!(spec["components"]["schemas"]["Project"].is_object());
        assert!(spec["components"]["schemas"]["ProjectStatus"].is_object());
        assert!(spec["components"]["schemas"]["ChecklistItem"].is_object());
        assert!(spec["components"]["schemas"]["SecurityAssessment"].is_object());
        assert!(spec["components"]["schemas"]["Error"].is_object());
    }

    #[test]
    fn test_openapi_has_security_schemes() {
        let spec = generate_openapi_spec();
        assert!(spec["components"]["securitySchemes"]["BearerAuth"].is_object());
        assert!(spec["components"]["securitySchemes"]["ApiKeyAuth"].is_object());
    }

    #[test]
    fn test_openapi_spec_serializable() {
        let spec = generate_openapi_spec();
        let json = serde_json::to_string(&spec);
        assert!(json.is_ok());

        let pretty_json = serde_json::to_string_pretty(&spec);
        assert!(pretty_json.is_ok());
    }

    #[test]
    fn test_openapi_endpoints_have_descriptions() {
        let spec = generate_openapi_spec();

        // Check /api/health endpoint
        let health_get = &spec["paths"]["/api/health"]["get"];
        assert!(health_get["summary"].is_string());
        assert!(health_get["description"].is_string());

        // Check /api/projects endpoint
        let projects_get = &spec["paths"]["/api/projects"]["get"];
        assert!(projects_get["summary"].is_string());
        assert!(projects_get["description"].is_string());
    }

    #[test]
    fn test_openapi_endpoints_have_responses() {
        let spec = generate_openapi_spec();

        // Check /api/health endpoint has 200 response
        let health_responses = &spec["paths"]["/api/health"]["get"]["responses"];
        assert!(health_responses["200"].is_object());

        // Check /api/projects endpoint has multiple responses
        let projects_responses = &spec["paths"]["/api/projects"]["get"]["responses"];
        assert!(projects_responses["200"].is_object());
        assert!(projects_responses["401"].is_object());
    }

    #[test]
    fn test_openapi_has_tags() {
        let spec = generate_openapi_spec();
        assert!(spec["tags"].is_array());
        let tags = spec["tags"].as_array().unwrap();
        assert!(!tags.is_empty());
    }

    #[test]
    fn test_openapi_servers_configured() {
        let spec = generate_openapi_spec();
        let servers = spec["servers"].as_array().unwrap();
        assert!(servers.len() >= 2);
        assert_eq!(servers[0]["url"], "http://localhost:3000");
        assert_eq!(servers[1]["url"], "https://api.lifecycle.example.com");
    }
}
