lumina-framework 0.1.2

A beautiful, fast, and elegant web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
use chrono::Local;
use std::fs;
use std::path::Path;

pub mod tinker;

pub async fn handle_make_controller(name: &str) {
    let file_name = camel_to_snake(name);
    let path_str = format!("src/app/controllers/{}.rs", file_name);
    let path = Path::new(&path_str);

    if path.exists() {
        println!("❌ Controller {} sudah ada!", path_str);
        return;
    }

    let stub = include_str!("stubs/controller.stub");
    let content = stub.replace("{{name}}", name);

    if let Err(e) = fs::write(path, content) {
        println!("❌ Gagal membuat controller: {}", e);
    } else {
        println!("✅ Controller berhasil dibuat: {}", path_str);
        let mod_file = "src/app/controllers/mod.rs";
        if let Ok(content) = fs::read_to_string(mod_file) {
            let mod_line = format!("pub mod {};", file_name);
            if !content.contains(&mod_line) {
                let mut f = fs::OpenOptions::new().append(true).open(mod_file).unwrap();
                use std::io::Write;
                let _ = writeln!(f, "pub mod {};", file_name);
                println!("✅ Controller auto-registered in controllers/mod.rs");
            }
        }
    }
}

pub async fn handle_make_model(name: &str) {
    let file_name = camel_to_snake(name);
    let path_str = format!("src/app/models/{}.rs", file_name);
    let path = Path::new(&path_str);

    if path.exists() {
        println!("❌ Model {} sudah ada!", path_str);
        return;
    }

    let stub = include_str!("stubs/model.stub");
    let content = stub
        .replace("{{name}}", name)
        .replace("{{table_name}}", &format!("{}s", file_name));

    if let Err(e) = fs::write(path, content) {
        println!("❌ Gagal membuat model: {}", e);
    } else {
        println!("✅ Model berhasil dibuat: {}", path_str);
        let mod_file = "src/app/models/mod.rs";
        if let Ok(content) = fs::read_to_string(mod_file) {
            let mod_line = format!("pub mod {};", file_name);
            if !content.contains(&mod_line) {
                let mut f = fs::OpenOptions::new().append(true).open(mod_file).unwrap();
                use std::io::Write;
                let _ = writeln!(f, "pub mod {};", file_name);
                println!("✅ Model auto-registered in models/mod.rs");
            }
        }
    }
}

pub async fn handle_make_migration(name: &str) {
    let timestamp = Local::now().format("%Y%m%d%H%M%S");
    let path_str = format!("database/migrations/{}_{}.sql", timestamp, name);
    let path = Path::new(&path_str);

    if let Err(e) = fs::write(path, "-- Migration file created by Lumina CLI\n") {
        println!("❌ Gagal membuat migration: {}", e);
    } else {
        println!("✅ Migration berhasil dibuat: {}", path_str);
    }
}

pub async fn handle_make_job(name: &str) {
    let file_name = camel_to_snake(name);
    let path_str = format!("src/app/jobs/{}.rs", file_name);
    let path = Path::new(&path_str);

    if path.exists() {
        println!("❌ Job {} sudah ada!", path_str);
        return;
    }

    let stub = include_str!("stubs/job.stub");
    let content = stub.replace("{{name}}", name);

    if let Err(e) = fs::write(path, content) {
        println!("❌ Gagal membuat job: {}", e);
    } else {
        println!("✅ Job berhasil dibuat: {}", path_str);
        println!("📌 Jangan lupa daftarkan di src/app/jobs/mod.rs");
    }
}

pub async fn handle_make_request(name: &str) {
    let file_name = camel_to_snake(name);
    let path_str = format!("src/app/requests/{}.rs", file_name);
    let path = Path::new(&path_str);

    if path.exists() {
        println!("❌ Request {} sudah ada!", path_str);
        return;
    }

    let stub = include_str!("stubs/request.stub");
    let content = stub.replace("{{name}}", name);

    if let Err(e) = fs::write(path, content) {
        println!("❌ Gagal membuat request: {}", e);
    } else {
        println!("✅ Request berhasil dibuat: {}", path_str);
        let mod_file = "src/app/requests/mod.rs";
        if let Ok(content) = fs::read_to_string(mod_file) {
            let mod_line = format!("pub mod {};", file_name);
            if !content.contains(&mod_line) {
                let mut f = fs::OpenOptions::new().append(true).open(mod_file).unwrap();
                use std::io::Write;
                let _ = writeln!(f, "pub mod {};", file_name);
                println!("✅ Request auto-registered in requests/mod.rs");
            }
        }
    }
}

pub async fn handle_new(name: &str) {
    println!("✨ Memulai pembuatan project Lumina baru: {}...", name);

    let path = Path::new(name);
    if path.exists() {
        println!("❌ Error: Direktori {} sudah ada!", name);
        return;
    }

    println!("🚀 Cloning Lumina Skeleton...");
    let status = std::process::Command::new("git")
        .arg("clone")
        .arg("--depth")
        .arg("1")
        .arg("https://github.com/lumina-java/framework.git")
        .arg(name)
        .status();

    match status {
        Ok(s) if s.success() => {
            println!("✅ Project berhasil di-clone.");

            // Cleanup .git folder to make it a fresh project
            let git_dir = path.join(".git");
            if git_dir.exists() {
                let _ = fs::remove_dir_all(git_dir);
            }

            // Setup .env
            let env_example = path.join(".env.example");
            let env_file = path.join(".env");
            if env_example.exists() && !env_file.exists() {
                let _ = fs::copy(env_example, env_file);
                println!("✅ Setup .env selesai.");
            }

            // Initialize fresh git repository
            let _ = std::process::Command::new("git")
                .arg("init")
                .current_dir(path)
                .status();
            println!("✅ Initialize fresh git repository.");

            println!("\n🎉 Project {} siap digunakan!", name);
            println!("👉 Jalankan perintah berikut:");
            println!("   cd {}", name);
            println!("   cargo run --bin lumina-server\n");
        }
        _ => {
            println!("❌ Gagal melakukan cloning. Pastikan 'git' sudah terinstall.");
        }
    }
}

pub async fn handle_make_service(name: &str) {
    let file_name = camel_to_snake(name);
    let path_str = format!("src/app/services/{}.rs", file_name);
    let path = Path::new(&path_str);

    if path.exists() {
        println!("❌ Service {} sudah ada!", path_str);
        return;
    }

    // Ekstrak nama model dari nama service (misal: UserService -> User)
    let model_camel = name.replace("Service", "");
    let model_snake = camel_to_snake(&model_camel);
    let table_name = format!("{}s", model_snake);

    let stub = include_str!("stubs/service.stub");
    let content = stub
        .replace("{{name}}", &model_camel)
        .replace("{{snake_name}}", &model_snake)
        .replace("{{table_name}}", &table_name);

    if let Err(e) = fs::write(path, content) {
        println!("❌ Gagal membuat service: {}", e);
    } else {
        println!("✅ Service berhasil dibuat: {}", path_str);
        let mod_file = "src/app/services/mod.rs";
        if let Ok(content) = fs::read_to_string(mod_file) {
            let mod_line = format!("pub mod {};", file_name);
            if !content.contains(&mod_line) {
                let mut f = fs::OpenOptions::new().append(true).open(mod_file).unwrap();
                use std::io::Write;
                let _ = writeln!(f, "pub mod {};", file_name);
                println!("✅ Service auto-registered in services/mod.rs");
            }
        }
    }
}

pub async fn handle_make_crud(name: &str, field_args: Vec<String>) {
    let snake_name = camel_to_snake(name);
    let table_name = format!("{}s", snake_name);

    // Parse fields
    let fields = parse_fields(field_args);

    // 1. Generate Model
    handle_make_model_with_fields(name, &fields).await;

    // 2. Generate Migration
    let migration_name = format!("create_{}_table", table_name);
    handle_make_migration_with_fields(&migration_name, &table_name, &fields).await;

    // 3. Generate Service
    let service_name = format!("{}Service", name);
    handle_make_service_with_fields(&service_name, &fields).await;

    // 4. Generate Request
    let request_name = format!("{}Request", name);
    let req_file_name = camel_to_snake(&request_name);
    let req_path_str = format!("src/app/requests/{}.rs", req_file_name);
    let req_path = Path::new(&req_path_str);
    if !req_path.exists() {
        let stub = include_str!("stubs/crud_request.stub");

        let mut field_code = String::new();
        for field in &fields {
            let rules = if field.rules.is_empty() {
                ""
            } else {
                &format!("#[rule(\"{}\")]\n    ", field.rules)
            };
            field_code.push_str(&format!(
                "{}pub {}: {},\n    ",
                rules,
                field.name,
                field.rust_type()
            ));
        }

        let content = stub
            .replace("{{name}}", name)
            .replace("{{fields}}", &field_code);
        let _ = fs::write(req_path, content);
        println!("✅ CRUD Request berhasil dibuat: {}", req_path_str);

        let mod_file = "src/app/requests/mod.rs";
        if let Ok(content) = fs::read_to_string(mod_file) {
            let mod_line = format!("pub mod {};", req_file_name);
            if !content.contains(&mod_line) {
                let mut f = fs::OpenOptions::new().append(true).open(mod_file).unwrap();
                use std::io::Write;
                let _ = writeln!(f, "pub mod {};", req_file_name);
            }
        }
    }

    // 5. Generate Controller (using specialized CRUD stub)
    let controller_path_str = format!("src/app/controllers/{}_controller.rs", snake_name);
    let controller_path = Path::new(&controller_path_str);
    if !controller_path.exists() {
        let stub = include_str!("stubs/crud_controller.stub");

        let mut store_logic = String::new();
        let mut update_logic = String::new();
        let mut input_map = String::new();

        for field in &fields {
            store_logic.push_str(&format!(
                "item.{} = form.{}.clone();\n        ",
                field.name, field.name
            ));
            update_logic.push_str(&format!(
                "item.{} = form.{}.clone();\n        ",
                field.name, field.name
            ));
            input_map.push_str(&format!("\"{}\": form.{}, ", field.name, field.name));
        }

        let content = stub
            .replace("{{name}}", name)
            .replace("{{snake_name}}", &snake_name)
            .replace("{{table_name}}", &table_name)
            .replace("{{store_logic}}", &store_logic)
            .replace("{{update_logic}}", &update_logic)
            .replace("{{input_map}}", &input_map);

        let _ = fs::write(controller_path, content);
        println!(
            "✅ CRUD Controller berhasil dibuat: {}",
            controller_path_str
        );
    }

    // 6. Generate Views
    let view_dir = format!("resources/views/{}", snake_name);
    let _ = fs::create_dir_all(&view_dir);

    // Index View
    let mut th_cols = String::new();
    let mut td_cols = String::new();
    for field in &fields {
        th_cols.push_str(&format!(
            "<th class=\"px-6 py-4\">{}</th>\n                    ",
            field.name.to_uppercase()
        ));
        td_cols.push_str(&format!(
            "<td class=\"px-6 py-4\">{{{{ item.{} }}}}</td>\n                    ",
            field.name
        ));
    }

    // Create/Edit Form Fields
    let mut form_fields = String::new();
    for field in &fields {
        let input_type = match field.field_type.as_str() {
            "integer" => "number",
            "boolean" => "checkbox",
            _ => "text",
        };

        if field.field_type == "text" {
            form_fields.push_str(&format!(
                "<div>\n\
                 \x20   <label class=\"block text-sm font-medium text-slate-700 mb-1\">{}</label>\n\
                 \x20   <textarea name=\"{}\" class=\"w-full px-4 py-2 rounded-lg border border-slate-200 focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition-all\" rows=\"4\">{{{{ item.{} | default(\"\") }}}}</textarea>\n\
                 </div>\n",
                field.name.to_uppercase(), field.name, field.name
            ));
        } else {
            form_fields.push_str(&format!(
                "<div>\n\
                 \x20   <label class=\"block text-sm font-medium text-slate-700 mb-1\">{}</label>\n\
                 \x20   <input type=\"{}\" name=\"{}\" value=\"{{{{ item.{} | default(\"\") }}}}\" class=\"w-full px-4 py-2 rounded-lg border border-slate-200 focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition-all\">\n\
                 </div>\n",
                field.name.to_uppercase(), input_type, field.name, field.name
            ));
        }
    }

    let view_stubs = [
        (
            "index.blade.rs",
            include_str!("stubs/view_index.stub"),
            vec![("{{th_cols}}", th_cols), ("{{td_cols}}", td_cols)],
        ),
        (
            "create.blade.rs",
            include_str!("stubs/view_create.stub"),
            vec![("{{form_fields}}", form_fields.clone())],
        ),
        (
            "edit.blade.rs",
            include_str!("stubs/view_edit.stub"),
            vec![("{{form_fields}}", form_fields)],
        ),
    ];

    for (file, stub, replacements) in view_stubs {
        let view_path = format!("{}/{}", view_dir, file);
        if !Path::new(&view_path).exists() {
            let mut content = stub
                .replace("{{ name }}", name)
                .replace("{{ snake_name }}", &snake_name);
            for (from, to) in replacements {
                content = content.replace(from, &to);
            }
            let _ = fs::write(&view_path, content);
            println!("✅ View berhasil dibuat: {}", view_path);
        }
    }

    // 7. Auto Registration: Model, Controller, Routes, etc.
    let mod_file = "src/app/models/mod.rs";
    if let Ok(content) = fs::read_to_string(mod_file) {
        let mod_line = format!("pub mod {};", snake_name);
        if !content.contains(&mod_line) {
            let mut f = fs::OpenOptions::new().append(true).open(mod_file).unwrap();
            use std::io::Write;
            let _ = writeln!(f, "pub mod {};", snake_name);
            println!("✅ Model registered in models/mod.rs");
        }
    }

    let ctrl_mod_file = "src/app/controllers/mod.rs";
    if let Ok(content) = fs::read_to_string(ctrl_mod_file) {
        let mod_line = format!("pub mod {}_controller;", snake_name);
        if !content.contains(&mod_line) {
            let mut f = fs::OpenOptions::new()
                .append(true)
                .open(ctrl_mod_file)
                .unwrap();
            use std::io::Write;
            let _ = writeln!(f, "pub mod {}_controller;", snake_name);
            println!("✅ Controller registered in controllers/mod.rs");
        }
    }

    let web_routes_file = "routes/web.rs";
    if let Ok(mut content) = fs::read_to_string(web_routes_file) {
        let import_line = format!(
            "use crate::app::controllers::{}_controller::{}Controller;\n",
            snake_name, name
        );
        if !content.contains(&import_line) {
            content.insert_str(0, &import_line);
        }

        let routes = format!(
            "        // {} CRUD Routes\n\
             \x20       .get(\"/{books}\", {name}Controller::index)\n\
             \x20       .get(\"/{books}/create\", {name}Controller::create)\n\
             \x20       .post(\"/{books}\", {name}Controller::store)\n\
             \x20       .get(\"/{books}/:id/edit\", {name}Controller::edit)\n\
             \x20       .post(\"/{books}/:id\", {name}Controller::update)\n\
             \x20       .get(\"/{books}/:id/delete\", {name}Controller::delete)\n\x20\x20\x20\x20\x20\x20\x20\x20",
            name,
            name = name,
            books = table_name
        );

        if !content.contains(&format!("/{books}", books = table_name)) {
            if let Some(pos) = content.find("        // Debug") {
                content.insert_str(pos, &routes);
            } else if let Some(pos) = content.find("    // ─── Protected Routes") {
                content.insert_str(pos, &routes);
            }
        }

        let _ = fs::write(web_routes_file, content);
        println!("✅ Registered routes in routes/web.rs");
    }

    // Menu registration ...
    let layout_file = "resources/views/layout.blade.rs";
    if let Ok(mut content) = fs::read_to_string(layout_file) {
        let menu_item = format!(
            "                    <li class=\"nav-item\"><a class=\"nav-link\" href=\"/{}\">{}</a></li>\n",
            table_name, name
        );
        if !content.contains(&format!("href=\"/{}\"", table_name)) {
            if let Some(pos) = content
                .find("<li class=\"nav-item\"><a class=\"nav-link\" href=\"/about\">About</a></li>")
            {
                content.insert_str(pos + "<li class=\"nav-item\"><a class=\"nav-link\" href=\"/about\">About</a></li>\n".len(), &menu_item);
            }
            let _ = fs::write(layout_file, content);
            println!("✅ Menu item added in layout.blade.rs");
        }
    }

    // Auto Registration: Sidebar in dashboard.html
    let dashboard_file = "resources/views/dashboard.blade.rs";
    if let Ok(mut content) = fs::read_to_string(dashboard_file) {
        let sidebar_item = format!(
            "            <a href=\"/{books}\" class=\"flex items-center px-4 py-3 text-slate-300 hover:bg-slate-800 hover:text-white rounded-lg transition-colors\">\n\
             \x20               <svg class=\"w-5 h-5 mr-3\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\"><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01\"></path></svg>\n\
             \x20               {name}s\n\
             \x20           </a>\n",
            books = table_name,
            name = name
        );
        if !content.contains(&format!("href=\"/{}\"", table_name)) {
            if let Some(pos) = content.find("</a>\n            <a href=\"/\"") {
                content.insert_str(pos + "</a>\n".len(), &sidebar_item);
            }
            let _ = fs::write(dashboard_file, content);
            println!("✅ Sidebar item added in dashboard.blade.rs");
        }
    }

    // Auto Registration: Sidebar in dashboard/index.html
    let dashboard_idx_file = "resources/views/dashboard/index.blade.rs";
    if let Ok(mut content) = fs::read_to_string(dashboard_idx_file) {
        let sidebar_item = format!(
            "            <a href=\"/{books}\"\n\
             \x20               class=\"flex items-center px-4 py-3 text-slate-300 hover:bg-slate-800 hover:text-white rounded-lg transition-all duration-200\">\n\
             \x20               <svg class=\"w-5 h-5 mr-3\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\"><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01\"></path></svg>\n\
             \x20               {name}s\n\
             \x20           </a>\n",
            books = table_name,
            name = name
        );
        if !content.contains(&format!("href=\"/{}\"", table_name)) {
            if let Some(pos) = content.find("</a>\n            <a href=\"/\"") {
                content.insert_str(pos + "</a>\n".len(), &sidebar_item);
            }
            let _ = fs::write(dashboard_idx_file, content);
            println!("✅ Sidebar item added in dashboard/index.blade.rs");
        }
    }

    println!("\n🚀 CRUD Blueprint Selesai!");
}

pub async fn handle_make_auth() {
    let path_str = "src/app/controllers/auth_controller.rs";
    let path = Path::new(&path_str);

    if path.exists() {
        println!("❌ AuthController {} sudah ada!", path_str);
    } else {
        let stub = include_str!("stubs/auth_controller.stub");
        if let Err(e) = fs::write(path, stub) {
            println!("❌ Gagal membuat AuthController: {}", e);
        } else {
            println!("✅ AuthController berhasil dibuat: {}", path_str);
        }
    }

    let view_dir = "resources/views/auth";
    let _ = fs::create_dir_all(&view_dir);

    let view_stubs = [
        ("login.blade.rs", include_str!("stubs/view_login.stub")),
        (
            "register.blade.rs",
            include_str!("stubs/view_register.stub"),
        ),
    ];

    for (file, stub) in view_stubs {
        let view_path = format!("{}/{}", view_dir, file);
        if !Path::new(&view_path).exists() {
            let _ = fs::write(&view_path, stub);
            println!("✅ Auth View berhasil dibuat: {}", view_path);
        }
    }

    println!("\n🚀 Auth Scaffolding Selesai!");
    println!("📌 Selesaikan langkah berikut:");
    println!("1. Daftarkan AuthController di src/app/controllers/mod.rs");
    println!("2. Daftarkan routes autentikasi di routes/web.rs");
}

pub async fn handle_migrate() {
    let config = crate::core::config::ConfigManager::new();
    let db_url = config.get_db_url();
    println!("🔄 Menjalankan migrasi database...");
    match crate::database::connection::DatabasePool::connect(&db_url).await {
        Ok(pool) => match crate::database::migration::run_migrations(&pool.pool, pool.kind).await {
            Ok(_) => println!("✅ Semua migrasi berhasil dijalankan."),
            Err(e) => println!("❌ Gagal menjalankan migrasi: {}", e),
        },
        Err(e) => println!("❌ Gagal connect ke database: {}", e),
    }
}

pub async fn handle_migrate_status() {
    let config = crate::core::config::ConfigManager::new();
    let db_url = config.get_db_url();
    match crate::database::connection::DatabasePool::connect(&db_url).await {
        Ok(pool) => {
            if let Err(e) = crate::database::migration::migrate_status(&pool.pool).await {
                println!("❌ Gagal cek status migrasi: {}", e);
            }
        }
        Err(e) => println!("❌ Gagal connect ke database: {}", e),
    }
}

pub async fn handle_migrate_rollback() {
    let config = crate::core::config::ConfigManager::new();
    let db_url = config.get_db_url();
    match crate::database::connection::DatabasePool::connect(&db_url).await {
        Ok(pool) => {
            if let Err(e) = crate::database::migration::migrate_rollback(&pool.pool).await {
                println!("❌ Gagal rollback migrasi: {}", e);
            }
        }
        Err(e) => println!("❌ Gagal connect ke database: {}", e),
    }
}

pub async fn handle_make_seeder(name: &str) {
    let file_name = camel_to_snake(name);
    let path_str = format!("database/seeders/{}.rs", file_name);
    let path = Path::new(&path_str);

    if path.exists() {
        println!("❌ Seeder {} sudah ada!", path_str);
        return;
    }

    let stub = include_str!("stubs/seeder.stub");
    let content = stub.replace("{{name}}", name);

    if let Err(e) = fs::write(path, content) {
        println!("❌ Gagal membuat seeder: {}", e);
    } else {
        println!("✅ Seeder berhasil dibuat: {}", path_str);
        println!("📌 Jangan lupa daftarkan di database/seeders/mod.rs");
    }
}

pub async fn handle_make_factory(name: &str) {
    let file_name = camel_to_snake(name);
    let path_str = format!("database/factories/{}.rs", file_name);
    let path = Path::new(&path_str);

    if path.exists() {
        println!("❌ Factory {} sudah ada!", path_str);
        return;
    }

    // Ekstrak nama model dari nama factory (misal: UserFactory -> User)
    let model_camel = name.replace("Factory", "");
    let model_snake = camel_to_snake(&model_camel);

    let stub = include_str!("stubs/factory.stub");
    let content = stub
        .replace("{{name}}", name)
        .replace("{{model_camel}}", &model_camel)
        .replace("{{model_snake}}", &model_snake);

    if let Err(e) = fs::write(path, content) {
        println!("❌ Gagal membuat factory: {}", e);
    } else {
        println!("✅ Factory berhasil dibuat: {}", path_str);
        println!("📌 Jangan lupa daftarkan di database/factories/mod.rs");
    }
}

pub async fn handle_db_seed() {
    let config = crate::core::config::ConfigManager::new();
    let db_url = config.get_db_url();
    match crate::database::connection::DatabasePool::connect(&db_url).await {
        Ok(_) => {
            println!("🌱 Please run seeding from your application main entry.");
        }
        Err(e) => println!("❌ Gagal connect ke database: {}", e),
    }
}

pub async fn handle_tinker() {
    let config = crate::core::config::ConfigManager::new();
    let db_url = config.get_db_url();
    match crate::database::connection::DatabasePool::connect(&db_url).await {
        Ok(pool) => {
            if let Err(e) = tinker::run(&pool).await {
                println!("❌ Tinker error: {}", e);
            }
        }
        Err(e) => println!("❌ Gagal connect ke database: {}", e),
    }
}

pub async fn handle_make_docker() {
    let dockerfile_path = "Dockerfile";
    let docker_compose_path = "docker-compose.yml";

    let dockerfile_content = include_str!("stubs/dockerfile.stub");
    let docker_compose_content = include_str!("stubs/docker-compose.stub");

    let _ = fs::write(dockerfile_path, dockerfile_content);
    let _ = fs::write(docker_compose_path, docker_compose_content);

    println!("✅ Dockerfile & docker-compose.yml berhasil dibuat.");
    handle_make_deployment_guide().await;
}

pub async fn handle_make_nginx() {
    let nginx_dir = "nginx";
    let _ = fs::create_dir_all(nginx_dir);
    let nginx_conf_path = format!("{}/nginx.conf", nginx_dir);

    let content = include_str!("stubs/nginx.stub");
    let _ = fs::write(&nginx_conf_path, content);

    println!(
        "✅ Konfigurasi Nginx berhasil dibuat di: {}",
        nginx_conf_path
    );
    handle_make_deployment_guide().await;
}

pub async fn handle_make_supervisor() {
    let supervisor_dir = "supervisor";
    let _ = fs::create_dir_all(supervisor_dir);
    let supervisor_conf_path = format!("{}/lumina.conf", supervisor_dir);

    let content = include_str!("stubs/supervisor.stub");
    let _ = fs::write(&supervisor_conf_path, content);

    println!(
        "✅ Konfigurasi Supervisor berhasil dibuat di: {}",
        supervisor_conf_path
    );
    handle_make_deployment_guide().await;
}

async fn handle_make_deployment_guide() {
    let guide_path = "docs/DEPLOYMENT.md";
    let _ = fs::create_dir_all("docs");

    let content = r#"# 🚀 Lumina Framework Deployment Guide

Panduan ini menjelaskan langkah-langkah untuk mendeploy aplikasi Lumina Framework ke lingkungan produksi dengan standar industri.

---

## 1. 🐳 Deployment dengan Docker (Direkomendasikan)

Lumina dilengkapi dengan konfigurasi Docker yang siap pakai (production-ready).

### Persiapan
1. Pastikan Docker dan Docker Compose terinstall di server.
2. Jalankan perintah scaffolding docker:
   ```bash
   ./lumina make:docker
   ```

### Menjalankan Aplikasi
Cukup jalankan satu perintah:
```bash
docker-compose up -d --build
```
Aplikasi akan berjalan di port `8000`, Nginx di port `80/443`, PostgreSQL di port `5432`, dan Redis di port `6379`.

---

## 2. 🛠️ Deployment Manual (Ubuntu/Debian)

Jika Anda ingin mengontrol setiap komponen secara manual di VPS.

### A. Install Dependencies
```bash
sudo apt update && sudo apt install -y pkg-config libssl-dev build-essential postgresql redis-server nginx supervisor
```

### B. Build Aplikasi
1. Clone repository ke server.
2. Build binary release:
   ```bash
   cargo build --release
   ```
3. Binary akan berada di `target/release/lumina-server`.

### C. Konfigurasi Database & Environment
1. Salin `.env.example` menjadi `.env`.
2. Update `DATABASE_URL` dan `APP_ENV=production`.
3. Jalankan migrasi:
   ```bash
   ./target/release/lumina migrate
   ```

---

## 3. 🛡️ Konfigurasi Nginx (Reverse Proxy)

Gunakan Nginx untuk menangani traffic HTTP/HTTPS dan static files.

1. Jalankan `./lumina make:nginx`.
2. Salin isi `nginx/nginx.conf` ke `/etc/nginx/sites-available/lumina`.
3. Aktifkan site dan restart Nginx:
   ```bash
   sudo ln -s /etc/nginx/sites-available/lumina /etc/nginx/sites-enabled/
   sudo nginx -t
   sudo systemctl restart nginx
   ```

---

## 4. 🔄 Process Management (Supervisor)

Gunakan Supervisor untuk memastikan aplikasi tetap berjalan (auto-restart) jika terjadi crash.

1. Jalankan `./lumina make:supervisor`.
2. Salin konfigurasi ke folder Supervisor:
   ```bash
   sudo cp supervisor/lumina.conf /etc/supervisor/conf.d/
   sudo supervisorctl reread
   sudo supervisorctl update
   sudo supervisorctl start all
   ```

---

## 5. 📝 Production Checklist

- [ ] **Security**: Ganti `APP_KEY` dan pastikan password database kuat.
- [ ] **SSL**: Gunakan Certbot untuk mendapatkan sertifikat SSL gratis.
- [ ] **Logging**: Cek log di `storage/logs/` secara berkala.
- [ ] **Backups**: Jalankan `./lumina backup:run` secara terjadwal menggunakan Cron.

---

Lumina Framework - *Advanced Agentic Coding*
"#;

    let _ = fs::write(guide_path, content);
}

pub async fn handle_backup() {
    println!("🔄 Memulai proses backup...");
    let config = crate::core::config::ConfigManager::new();
    let db_url = config.get_db_url();
    let db_conn = std::env::var("DB_CONNECTION").unwrap_or_else(|_| "sqlite".to_string());

    let manager = crate::core::backup::BackupManager::new();
    match manager.run_full_backup(&db_conn, &db_url).await {
        Ok(path) => println!("✅ Backup berhasil dibuat: {}", path),
        Err(e) => println!("❌ Backup gagal: {}", e),
    }
}

fn camel_to_snake(s: &str) -> String {
    let mut snake = String::new();
    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() && i > 0 {
            snake.push('_');
        }
        snake.push(c.to_lowercase().next().unwrap());
    }
    snake
}

struct Field {
    name: String,
    field_type: String,
    rules: String,
}

impl Field {
    fn rust_type(&self) -> &str {
        match self.field_type.as_str() {
            "integer" => "i64",
            "boolean" => "bool",
            "date" => "chrono::NaiveDate",
            _ => "String",
        }
    }

    fn sql_type(&self) -> &str {
        match self.field_type.as_str() {
            "integer" => "INTEGER",
            "boolean" => "BOOLEAN",
            "date" => "DATE",
            "text" => "TEXT",
            _ => "VARCHAR(255)",
        }
    }
}

fn parse_fields(args: Vec<String>) -> Vec<Field> {
    let mut fields = Vec::new();
    for arg in args {
        let parts: Vec<&str> = arg.split(':').collect();
        if parts.len() >= 2 {
            fields.push(Field {
                name: parts[0].to_string(),
                field_type: parts[1].to_string(),
                rules: if parts.len() >= 3 {
                    parts[2..].join("|")
                } else {
                    String::new()
                },
            });
        }
    }

    // Add default name if no fields provided
    if fields.is_empty() {
        fields.push(Field {
            name: "name".to_string(),
            field_type: "string".to_string(),
            rules: "required|min:3".to_string(),
        });
    }

    fields
}

async fn handle_make_model_with_fields(name: &str, fields: &[Field]) {
    let file_name = camel_to_snake(name);
    let path_str = format!("src/app/models/{}.rs", file_name);
    let path = Path::new(&path_str);

    if path.exists() {
        println!("❌ Model {} sudah ada!", path_str);
        return;
    }

    let stub = include_str!("stubs/model.stub");

    let mut field_code = String::new();
    let mut sql_fields = String::new();
    let mut sql_placeholders = String::new();
    let mut sql_update = String::new();
    let mut bind_fields = String::new();

    for field in fields {
        field_code.push_str(&format!("pub {}: {},\n    ", field.name, field.rust_type()));
        sql_fields.push_str(&format!("{}, ", field.name));
        sql_placeholders.push_str("?, ");
        sql_update.push_str(&format!("{} = ?, ", field.name));
        bind_fields.push_str(&format!(".bind(&self.{})", field.name));
    }

    let content = stub
        .replace("{{name}}", name)
        .replace("{{table_name}}", &format!("{}s", file_name))
        .replace("{{fields}}", &field_code)
        .replace("{{sql_fields}}", sql_fields.trim_end_matches(", "))
        .replace(
            "{{sql_placeholders}}",
            sql_placeholders.trim_end_matches(", "),
        )
        .replace("{{sql_update}}", sql_update.trim_end_matches(", "))
        .replace("{{bind_fields}}", &bind_fields);

    if let Err(e) = fs::write(path, content) {
        println!("❌ Gagal membuat model: {}", e);
    } else {
        println!("✅ Model berhasil dibuat: {}", path_str);
        let mod_file = "src/app/models/mod.rs";
        if let Ok(content) = fs::read_to_string(mod_file) {
            let mod_line = format!("pub mod {};", file_name);
            if !content.contains(&mod_line) {
                let mut f = fs::OpenOptions::new().append(true).open(mod_file).unwrap();
                use std::io::Write;
                let _ = writeln!(f, "pub mod {};", file_name);
            }
        }
    }
}

async fn handle_make_migration_with_fields(name: &str, table_name: &str, fields: &[Field]) {
    let timestamp = Local::now().format("%Y%m%d%H%M%S");
    let path_str = format!("database/migrations/{}_{}.sql", timestamp, name);
    let path = Path::new(&path_str);

    let mut sql = format!(
        "CREATE TABLE {} (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n",
        table_name
    );
    for field in fields {
        sql.push_str(&format!("    {} {},\n", field.name, field.sql_type()));
    }
    sql.push_str("    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n");
    sql.push_str("    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP\n);");

    if let Err(e) = fs::write(path, sql) {
        println!("❌ Gagal membuat migration: {}", e);
    } else {
        println!("✅ Migration berhasil dibuat: {}", path_str);
    }
}

async fn handle_make_service_with_fields(name: &str, _fields: &[Field]) {
    let file_name = camel_to_snake(name);
    let path_str = format!("src/app/services/{}.rs", file_name);
    let path = Path::new(&path_str);

    if path.exists() {
        println!("❌ Service {} sudah ada!", path_str);
        return;
    }

    let model_camel = name.replace("Service", "");
    let model_snake = camel_to_snake(&model_camel);
    let table_name = format!("{}s", model_snake);

    let stub = include_str!("stubs/service.stub");

    let content = stub
        .replace("{{name}}", &model_camel)
        .replace("{{snake_name}}", &model_snake)
        .replace("{{table_name}}", &table_name);

    if let Err(e) = fs::write(path, content) {
        println!("❌ Gagal membuat service: {}", e);
    } else {
        println!("✅ Service berhasil dibuat: {}", path_str);
        let mod_file = "src/app/services/mod.rs";
        if let Ok(content) = fs::read_to_string(mod_file) {
            let mod_line = format!("pub mod {};", file_name);
            if !content.contains(&mod_line) {
                let mut f = fs::OpenOptions::new().append(true).open(mod_file).unwrap();
                use std::io::Write;
                let _ = writeln!(f, "pub mod {};", file_name);
            }
        }
    }
}