1use std::{fs, path::PathBuf};
4
5use serde::{Deserialize, Serialize};
6
7use super::analyzer::Layer;
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct FieldDef {
12 pub name: String,
14 pub field_type: String,
16 #[serde(default)]
18 pub optional: bool,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct EntityRequest {
24 pub name: String,
26 pub fields: Vec<FieldDef>,
28 #[serde(default = "default_true")]
30 pub with_repository: bool,
31}
32
33fn default_true() -> bool {
34 true
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct ServiceRequest {
40 pub name: String,
42 #[serde(default)]
44 pub dependencies: Vec<String>,
45 #[serde(default)]
47 pub methods: Vec<MethodDef>,
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct MethodDef {
53 pub name: String,
55 #[serde(default)]
57 pub params: Vec<(String, String)>,
58 pub return_type: String,
60 #[serde(default = "default_true")]
62 pub is_async: bool,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct HandlerRequest {
68 pub name: String,
70 pub method: String,
72 pub path: String,
74 pub service: Option<String>,
76}
77
78#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct GenerationResult {
81 pub success: bool,
83 pub files_created: Vec<String>,
85 pub files_modified: Vec<String>,
87 pub error: Option<String>,
89}
90
91impl GenerationResult {
92 fn success(files_created: Vec<String>, files_modified: Vec<String>) -> Self {
93 Self {
94 success: true,
95 files_created,
96 files_modified,
97 error: None,
98 }
99 }
100
101 fn error(message: impl Into<String>) -> Self {
102 Self {
103 success: false,
104 files_created: vec![],
105 files_modified: vec![],
106 error: Some(message.into()),
107 }
108 }
109}
110
111pub struct CodeGenerator {
113 project_path: PathBuf,
114}
115
116impl CodeGenerator {
117 pub fn new(project_path: impl Into<PathBuf>) -> Self {
119 Self {
120 project_path: project_path.into(),
121 }
122 }
123
124 pub fn generate_entity(&self, request: &EntityRequest) -> GenerationResult {
126 let mut files_created = Vec::new();
127 let mut files_modified = Vec::new();
128
129 let entity_name = &request.name;
130 let snake_name = to_snake_case(entity_name);
131
132 let entity_content = self.generate_entity_content(request);
134 let entity_path = self
135 .project_path
136 .join("src/domain")
137 .join(format!("{}.rs", snake_name));
138
139 if let Err(e) = fs::write(&entity_path, entity_content) {
140 return GenerationResult::error(format!("Failed to write entity file: {}", e));
141 }
142 files_created.push(format!("src/domain/{}.rs", snake_name));
143
144 if request.with_repository {
146 let repo_content = self.generate_repository_content(entity_name);
147 let repo_path = self
148 .project_path
149 .join("src/domain")
150 .join(format!("{}_repository.rs", snake_name));
151
152 if let Err(e) = fs::write(&repo_path, repo_content) {
153 return GenerationResult::error(format!("Failed to write repository file: {}", e));
154 }
155 files_created.push(format!("src/domain/{}_repository.rs", snake_name));
156 }
157
158 if let Err(e) = self.update_mod_file(Layer::Domain, &snake_name, request.with_repository) {
160 return GenerationResult::error(format!("Failed to update mod.rs: {}", e));
161 }
162 files_modified.push("src/domain/mod.rs".to_string());
163
164 GenerationResult::success(files_created, files_modified)
165 }
166
167 fn generate_entity_content(&self, request: &EntityRequest) -> String {
169 let entity_name = &request.name;
170
171 let mut fields = String::new();
172 let mut has_uuid = false;
173 let mut has_chrono = false;
174
175 for field in &request.fields {
176 let field_type = if field.optional {
177 format!("Option<{}>", field.field_type)
178 } else {
179 field.field_type.clone()
180 };
181
182 if field.field_type.contains("Uuid") {
183 has_uuid = true;
184 }
185 if field.field_type.contains("DateTime") || field.field_type.contains("NaiveDate") {
186 has_chrono = true;
187 }
188
189 fields.push_str(&format!(" pub {}: {},\n", field.name, field_type));
190 }
191
192 let mut imports = String::new();
193 if has_uuid {
194 imports.push_str("use uuid::Uuid;\n");
195 }
196 if has_chrono {
197 imports.push_str("use chrono::{DateTime, Utc};\n");
198 }
199 imports.push_str("use serde::{Deserialize, Serialize};\n");
200
201 format!(
202 r#"//! {entity_name} entity
203
204{imports}
205/// {entity_name} domain entity
206#[derive(Debug, Clone, Serialize, Deserialize)]
207pub struct {entity_name} {{
208{fields}}}
209
210impl {entity_name} {{
211 /// Create a new {entity_name}
212 pub fn new({params}) -> Self {{
213 Self {{
214{field_assignments} }}
215 }}
216}}
217"#,
218 entity_name = entity_name,
219 imports = imports,
220 fields = fields.trim_end(),
221 params = request
222 .fields
223 .iter()
224 .map(|f| format!(
225 "{}: {}",
226 f.name,
227 if f.optional {
228 format!("Option<{}>", f.field_type)
229 } else {
230 f.field_type.clone()
231 }
232 ))
233 .collect::<Vec<_>>()
234 .join(", "),
235 field_assignments = request
236 .fields
237 .iter()
238 .map(|f| format!(" {},\n", f.name))
239 .collect::<String>()
240 )
241 }
242
243 fn generate_repository_content(&self, entity_name: &str) -> String {
245 let snake_name = to_snake_case(entity_name);
246
247 format!(
248 r#"//! {entity_name} repository trait
249
250use async_trait::async_trait;
251use uuid::Uuid;
252
253use super::{snake_name}::{entity_name};
254
255/// Repository error
256#[derive(Debug, thiserror::Error)]
257pub enum RepositoryError {{
258 #[error("Entity not found: {{0}}")]
259 NotFound(String),
260 #[error("Database error: {{0}}")]
261 Database(String),
262}}
263
264/// {entity_name} repository trait
265#[async_trait]
266pub trait {entity_name}Repository: Send + Sync {{
267 /// Find by ID
268 async fn find_by_id(&self, id: Uuid) -> Result<Option<{entity_name}>, RepositoryError>;
269
270 /// Find all
271 async fn find_all(&self) -> Result<Vec<{entity_name}>, RepositoryError>;
272
273 /// Save entity
274 async fn save(&self, entity: &{entity_name}) -> Result<(), RepositoryError>;
275
276 /// Delete by ID
277 async fn delete(&self, id: Uuid) -> Result<(), RepositoryError>;
278}}
279"#,
280 entity_name = entity_name,
281 snake_name = snake_name,
282 )
283 }
284
285 pub fn generate_service(&self, request: &ServiceRequest) -> GenerationResult {
287 let mut files_created = Vec::new();
288 let mut files_modified = Vec::new();
289
290 let snake_name = to_snake_case(&request.name);
291
292 let content = self.generate_service_content(request);
293 let service_path = self
294 .project_path
295 .join("src/application")
296 .join(format!("{}_service.rs", snake_name));
297
298 if let Err(e) = fs::write(&service_path, content) {
299 return GenerationResult::error(format!("Failed to write service file: {}", e));
300 }
301 files_created.push(format!("src/application/{}_service.rs", snake_name));
302
303 if let Err(e) = self.update_service_mod_file(&snake_name) {
305 return GenerationResult::error(format!("Failed to update mod.rs: {}", e));
306 }
307 files_modified.push("src/application/mod.rs".to_string());
308
309 GenerationResult::success(files_created, files_modified)
310 }
311
312 fn generate_service_content(&self, request: &ServiceRequest) -> String {
314 let service_name = format!("{}Service", request.name);
315
316 let mut deps_fields = String::new();
317 let mut deps_params = String::new();
318 let mut deps_init = String::new();
319
320 for (i, dep) in request.dependencies.iter().enumerate() {
321 let field_name = to_snake_case(dep);
322 deps_fields.push_str(&format!(" {}: Arc<dyn {}>,\n", field_name, dep));
323 deps_params.push_str(&format!("{}: Arc<dyn {}>", field_name, dep));
324 deps_init.push_str(&format!(" {},\n", field_name));
325 if i < request.dependencies.len() - 1 {
326 deps_params.push_str(", ");
327 }
328 }
329
330 let mut methods = String::new();
331 for method in &request.methods {
332 let async_kw = if method.is_async { "async " } else { "" };
333 let params: String = method
334 .params
335 .iter()
336 .map(|(name, ty)| format!("{}: {}", name, ty))
337 .collect::<Vec<_>>()
338 .join(", ");
339
340 methods.push_str(&format!(
341 r#"
342 /// {}
343 pub {async_kw}fn {name}(&self{params_sep}{params}) -> Result<{return_type}, {service_name}Error> {{
344 todo!("Implement {name}")
345 }}
346"#,
347 method.name,
348 async_kw = async_kw,
349 name = method.name,
350 params_sep = if params.is_empty() { "" } else { ", " },
351 params = params,
352 return_type = method.return_type,
353 service_name = service_name,
354 ));
355 }
356
357 format!(
358 r#"//! {service_name}
359
360use std::sync::Arc;
361
362use thiserror::Error;
363
364/// {service_name} error
365#[derive(Debug, Error)]
366pub enum {service_name}Error {{
367 #[error("Not found: {{0}}")]
368 NotFound(String),
369 #[error("Validation error: {{0}}")]
370 Validation(String),
371 #[error("Internal error: {{0}}")]
372 Internal(String),
373}}
374
375/// {service_name}
376pub struct {service_name} {{
377{deps_fields}}}
378
379impl {service_name} {{
380 /// Create a new {service_name}
381 pub fn new({deps_params}) -> Self {{
382 Self {{
383{deps_init} }}
384 }}
385{methods}}}
386"#,
387 service_name = service_name,
388 deps_fields = deps_fields,
389 deps_params = deps_params,
390 deps_init = deps_init,
391 methods = methods,
392 )
393 }
394
395 pub fn generate_handler(&self, request: &HandlerRequest) -> GenerationResult {
397 let mut files_created = Vec::new();
398 let mut files_modified = Vec::new();
399
400 let handler_path = self
401 .project_path
402 .join("src/presentation")
403 .join("handlers.rs");
404
405 let existing = fs::read_to_string(&handler_path).unwrap_or_default();
407
408 let new_handler = self.generate_handler_content(request);
409 let content = if existing.is_empty() {
410 self.generate_handlers_file(&[new_handler])
411 } else {
412 format!("{}\n\n{}", existing.trim_end(), new_handler)
414 };
415
416 if let Err(e) = fs::write(&handler_path, content) {
417 return GenerationResult::error(format!("Failed to write handler file: {}", e));
418 }
419
420 if existing.is_empty() {
421 files_created.push("src/presentation/handlers.rs".to_string());
422 } else {
423 files_modified.push("src/presentation/handlers.rs".to_string());
424 }
425
426 GenerationResult::success(files_created, files_modified)
427 }
428
429 fn generate_handler_content(&self, request: &HandlerRequest) -> String {
431 let method = request.method.to_uppercase();
432
433 format!(
434 r#"/// {method} {path}
435pub async fn {name}(
436 // State(service): State<Arc<{service}>>,
437 // Path(id): Path<Uuid>,
438) -> impl IntoResponse {{
439 // TODO: Implement handler
440 Json(serde_json::json!({{
441 "status": "ok",
442 "handler": "{name}"
443 }}))
444}}"#,
445 method = method,
446 path = request.path,
447 name = request.name,
448 service = request.service.as_deref().unwrap_or("AppService"),
449 )
450 }
451
452 fn generate_handlers_file(&self, handlers: &[String]) -> String {
454 format!(
455 r#"//! HTTP handlers
456
457use axum::{{
458 extract::{{Path, State}},
459 response::IntoResponse,
460 Json,
461}};
462use serde_json;
463use std::sync::Arc;
464use uuid::Uuid;
465
466{handlers}
467"#,
468 handlers = handlers.join("\n\n")
469 )
470 }
471
472 fn update_mod_file(
474 &self,
475 layer: Layer,
476 module_name: &str,
477 with_repository: bool,
478 ) -> Result<(), String> {
479 let mod_path = self
480 .project_path
481 .join("src")
482 .join(layer.dir_name())
483 .join("mod.rs");
484
485 let existing = fs::read_to_string(&mod_path).unwrap_or_default();
486
487 let mut content = existing.clone();
488
489 let mod_decl = format!("pub mod {};", module_name);
491 if !content.contains(&mod_decl) {
492 content = format!("{}\n{}", mod_decl, content);
493 }
494
495 let re_export = format!("pub use {}::*;", module_name);
497 if !content.contains(&re_export) && !content.contains(&format!("pub use {}::", module_name))
498 {
499 content.push_str(&format!("\n{}", re_export));
500 }
501
502 if with_repository {
504 let repo_mod = format!("pub mod {}_repository;", module_name);
505 if !content.contains(&repo_mod) {
506 content = format!("{}\n{}", repo_mod, content);
507 }
508 let repo_export = format!("pub use {}_repository::*;", module_name);
509 if !content.contains(&repo_export) {
510 content.push_str(&format!("\n{}", repo_export));
511 }
512 }
513
514 fs::write(&mod_path, content).map_err(|e| format!("Failed to write mod.rs: {}", e))
515 }
516
517 fn update_service_mod_file(&self, service_name: &str) -> Result<(), String> {
519 let mod_path = self.project_path.join("src/application/mod.rs");
520
521 let existing = fs::read_to_string(&mod_path).unwrap_or_default();
522 let mut content = existing.clone();
523
524 let mod_decl = format!("pub mod {}_service;", service_name);
525 if !content.contains(&mod_decl) {
526 content = format!("{}\n{}", mod_decl, content);
527 }
528
529 let re_export = format!("pub use {}_service::*;", service_name);
530 if !content.contains(&re_export) {
531 content.push_str(&format!("\n{}", re_export));
532 }
533
534 fs::write(&mod_path, content).map_err(|e| format!("Failed to write mod.rs: {}", e))
535 }
536}
537
538fn to_snake_case(s: &str) -> String {
540 let mut result = String::new();
541 for (i, c) in s.chars().enumerate() {
542 if c.is_uppercase() {
543 if i > 0 {
544 result.push('_');
545 }
546 result.push(c.to_lowercase().next().unwrap());
547 } else {
548 result.push(c);
549 }
550 }
551 result
552}
553
554#[cfg(test)]
555mod tests {
556 use super::*;
557
558 #[test]
559 fn test_to_snake_case() {
560 assert_eq!(to_snake_case("UserProfile"), "user_profile");
561 assert_eq!(to_snake_case("User"), "user");
562 assert_eq!(to_snake_case("HTTPClient"), "h_t_t_p_client");
563 }
564
565 #[test]
566 fn test_entity_request_serialization() {
567 let request = EntityRequest {
568 name: "User".to_string(),
569 fields: vec![
570 FieldDef {
571 name: "id".to_string(),
572 field_type: "Uuid".to_string(),
573 optional: false,
574 },
575 FieldDef {
576 name: "email".to_string(),
577 field_type: "String".to_string(),
578 optional: false,
579 },
580 ],
581 with_repository: true,
582 };
583
584 let json = serde_json::to_string(&request).unwrap();
585 assert!(json.contains("User"));
586 assert!(json.contains("email"));
587 }
588}