foundry-rs 0.1.2

Configuration-driven REST backend library for Rust with PostgreSQL — define schemas, tables, and APIs in JSON, get a production-grade REST service.
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
//! Build OpenAPI spec from architect._sys_* tables. Exposed at GET /spec.
//! APIs and paths come from _sys_api_entities per package; parameters and request/response body
//! schemas are built from _sys_columns (column names, types, nullable, default). Entity and KV
//! paths are generated dynamically by listing _sys_packages and loading each package's config.

use crate::case::to_camel_case;
use crate::config::{load_from_pool, resolve, KvStoreConfig, ResolvedEntity, ResolvedModel};
use crate::state::AppState;
use crate::store::list_package_ids;
use axum::extract::State;
use axum::Json;
use std::collections::HashMap;
use utoipa::openapi::path::{
    HttpMethod, Operation, OperationBuilder, Parameter, ParameterBuilder, ParameterIn,
    PathItemBuilder, PathsBuilder,
};
use utoipa::openapi::request_body::RequestBodyBuilder;
use utoipa::openapi::response::{Response, ResponsesBuilder};
use utoipa::openapi::schema::{ObjectBuilder, Schema, SchemaType, Type};
use utoipa::openapi::server::{ServerBuilder, ServerVariableBuilder};
use utoipa::openapi::{Content, Info, OpenApi, OpenApiBuilder, RefOr, Required};

/// Build server with URL `http://{host}:{port}` and variable defaults.
fn build_server() -> utoipa::openapi::server::Server {
    ServerBuilder::new()
        .url("http://{host}:{port}")
        .parameter(
            "host",
            ServerVariableBuilder::new()
                .default_value("localhost")
                .description(Some("API host")),
        )
        .parameter(
            "port",
            ServerVariableBuilder::new()
                .default_value("3000")
                .description(Some("API port")),
        )
        .build()
}

fn json_object_schema() -> Schema {
    Schema::Object(
        ObjectBuilder::new()
            .schema_type(SchemaType::new(Type::Object))
            .description(Some(
                "JSON object; keys may be in camelCase (e.g. entity fields).",
            ))
            .into(),
    )
}

/// Map PostgreSQL type (from _sys_columns) to OpenAPI schema type for parameters and body properties.
fn column_schema_from_pg_type(pg_type: Option<&str>) -> Schema {
    let t = pg_type.unwrap_or("").to_lowercase();
    // Handle PostgreSQL array types (e.g. uuid[], text[], _int4, _uuid) by mapping
    // them to OpenAPI arrays whose item schema is derived from the element type.
    if t.ends_with("[]") || t.starts_with('_') {
        let element_type = t.trim_end_matches("[]").trim_start_matches('_');
        let item_schema = column_schema_from_pg_type(Some(element_type));
        return Schema::Array(
            utoipa::openapi::schema::ArrayBuilder::new()
                .items(RefOr::T(item_schema))
                .build(),
        );
    }
    if t.contains("int") || t.contains("serial") {
        return Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::Integer))
                .into(),
        );
    }
    if t.contains("bool") {
        return Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::Boolean))
                .into(),
        );
    }
    if t.contains("uuid") {
        return Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::String))
                .format(Some(utoipa::openapi::schema::SchemaFormat::KnownFormat(
                    utoipa::openapi::schema::KnownFormat::Uuid,
                )))
                .into(),
        );
    }
    if t.contains("numeric")
        || t.contains("decimal")
        || t.contains("real")
        || t.contains("double")
        || t.contains("float")
    {
        return Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::Number))
                .into(),
        );
    }
    if t.contains("timestamp") || t.contains("date") {
        return Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::String))
                .format(Some(utoipa::openapi::schema::SchemaFormat::KnownFormat(
                    utoipa::openapi::schema::KnownFormat::DateTime,
                )))
                .into(),
        );
    }
    Schema::Object(
        utoipa::openapi::schema::ObjectBuilder::new()
            .schema_type(SchemaType::new(Type::String))
            .into(),
    )
}

/// Build OpenAPI object schema from entity columns (_sys_columns). Properties use camelCase.
/// For create: required = !nullable && !has_default. For update: all optional (partial).
fn entity_body_schema(entity: &ResolvedEntity, for_create: bool) -> Schema {
    let mut builder = utoipa::openapi::schema::ObjectBuilder::new()
        .schema_type(SchemaType::new(Type::Object))
        .description(Some(format!(
            "Fields from architect._sys_columns for table {} (API uses camelCase).",
            entity.table_id
        )));
    let mut required = Vec::new();
    for col in &entity.columns {
        if entity.sensitive_columns.contains(&col.name) {
            continue;
        }
        let camel = to_camel_case(&col.name);
        let prop_schema = column_schema_from_pg_type(col.pg_type.as_deref());
        builder = builder.property(camel.clone(), RefOr::T(prop_schema));
        if for_create && !col.nullable && !col.has_default {
            required.push(camel);
        }
    }
    for r in &required {
        builder = builder.required(r.clone());
    }
    Schema::Object(builder.into())
}

fn default_responses() -> ResponsesBuilder {
    ResponsesBuilder::new()
        .response("200", Response::new("OK"))
        .response("201", Response::new("Created"))
        .response("204", Response::new("No Content"))
        .response("400", Response::new("Bad Request"))
        .response("404", Response::new("Not Found"))
}

/// X-Tenant-ID header required for all config and entity APIs.
fn x_tenant_id_header() -> Parameter {
    ParameterBuilder::new()
        .name("X-Tenant-ID")
        .parameter_in(ParameterIn::Header)
        .required(Required::True)
        .description(Some(
            "Tenant id; must match a tenant in architect._sys_tenants (e.g. default-mode-1, default-mode-3).",
        ))
        .schema(Some(RefOr::T(Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::String))
                .into(),
        ))))
        .build()
}

/// Path parameter for package-scoped routes: packageId (from architect._sys_packages). No literal package ids in the spec.
fn package_id_param() -> Parameter {
    ParameterBuilder::new()
        .name("packageId")
        .parameter_in(ParameterIn::Path)
        .required(Required::True)
        .description(Some("Package id from architect._sys_packages."))
        .schema(Some(RefOr::T(Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::String))
                .into(),
        ))))
        .build()
}

fn list_operation(
    entity: &ResolvedEntity,
    op_suffix: &str,
    include_package_id_param: bool,
) -> Operation {
    let mut params = vec![x_tenant_id_header()];
    if include_package_id_param {
        params.push(package_id_param());
    }
    params.extend(vec![
        ParameterBuilder::new()
            .name("limit")
            .parameter_in(ParameterIn::Query)
            .required(Required::False)
            .description(Some("Max number of items to return"))
            .schema(Some(RefOr::T(Schema::Object(
                utoipa::openapi::schema::ObjectBuilder::new()
                    .schema_type(SchemaType::new(Type::Integer))
                    .into(),
            ))))
            .build(),
        ParameterBuilder::new()
            .name("offset")
            .parameter_in(ParameterIn::Query)
            .required(Required::False)
            .description(Some("Number of items to skip"))
            .schema(Some(RefOr::T(Schema::Object(
                utoipa::openapi::schema::ObjectBuilder::new()
                    .schema_type(SchemaType::new(Type::Integer))
                    .into(),
            ))))
            .build(),
        ParameterBuilder::new()
            .name("include")
            .parameter_in(ParameterIn::Query)
            .required(Required::False)
            .description(Some(
                "Comma-separated related entity path segments to include",
            ))
            .schema(Some(RefOr::T(Schema::Object(
                utoipa::openapi::schema::ObjectBuilder::new()
                    .schema_type(SchemaType::new(Type::String))
                    .into(),
            ))))
            .build(),
    ]);
    for col in &entity.columns {
        if entity.sensitive_columns.contains(&col.name) {
            continue;
        }
        let camel = to_camel_case(&col.name);
        let schema = column_schema_from_pg_type(col.pg_type.as_deref());
        params.push(
            ParameterBuilder::new()
                .name(camel)
                .parameter_in(ParameterIn::Query)
                .required(Required::False)
                .description(Some(format!("Filter by {} (from _sys_columns)", col.name)))
                .schema(Some(RefOr::T(schema)))
                .build(),
        );
    }
    OperationBuilder::new()
        .summary(Some(format!("List {}", entity.path_segment)))
        .description(Some(format!(
            "List {} with optional filters, pagination (limit, offset), and includes.",
            entity.path_segment
        )))
        .operation_id(Some(format!("list_{}{}", entity.path_segment, op_suffix)))
        .parameters(Some(params))
        .responses(default_responses().build())
        .build()
}

fn create_operation(
    entity: &ResolvedEntity,
    op_suffix: &str,
    include_package_id_param: bool,
) -> Operation {
    let mut params = vec![x_tenant_id_header()];
    if include_package_id_param {
        params.push(package_id_param());
    }
    let body = RequestBodyBuilder::new()
        .description(Some(format!(
            "JSON object with {} fields from _sys_columns (camelCase). PK may be omitted if DB default exists.",
            entity.path_segment
        )))
        .content(
            "application/json",
            Content::new(Some(RefOr::T(entity_body_schema(entity, true)))),
        )
        .required(Some(Required::True))
        .build();
    OperationBuilder::new()
        .summary(Some(format!("Create {}", entity.path_segment)))
        .description(Some(format!("Create a single {}", entity.path_segment)))
        .operation_id(Some(format!("create_{}{}", entity.path_segment, op_suffix)))
        .parameters(Some(params))
        .request_body(Some(body))
        .responses(
            ResponsesBuilder::new()
                .response("201", Response::new("Created"))
                .response("400", Response::new("Bad Request"))
                .build(),
        )
        .build()
}

fn read_operation(
    entity: &ResolvedEntity,
    op_suffix: &str,
    include_package_id_param: bool,
) -> Operation {
    let mut params = vec![x_tenant_id_header()];
    if include_package_id_param {
        params.push(package_id_param());
    }
    let id_param = ParameterBuilder::new()
        .name("id")
        .parameter_in(ParameterIn::Path)
        .required(Required::True)
        .description(Some(
            "Entity ID (UUID, integer, or text depending on table PK)",
        ))
        .schema(Some(RefOr::T(Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::String))
                .into(),
        ))))
        .build();
    let include_param = ParameterBuilder::new()
        .name("include")
        .parameter_in(ParameterIn::Query)
        .required(Required::False)
        .description(Some(
            "Comma-separated related entity path segments to include",
        ))
        .schema(Some(RefOr::T(Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::String))
                .into(),
        ))))
        .build();
    params.push(id_param);
    params.push(include_param);
    OperationBuilder::new()
        .summary(Some(format!("Get {} by id", entity.path_segment)))
        .description(Some(format!("Get a single {} by id.", entity.path_segment)))
        .operation_id(Some(format!("read_{}{}", entity.path_segment, op_suffix)))
        .parameters(Some(params))
        .responses(default_responses().build())
        .build()
}

fn update_operation(
    entity: &ResolvedEntity,
    op_suffix: &str,
    include_package_id_param: bool,
) -> Operation {
    let mut params = vec![x_tenant_id_header()];
    if include_package_id_param {
        params.push(package_id_param());
    }
    let id_param = ParameterBuilder::new()
        .name("id")
        .parameter_in(ParameterIn::Path)
        .required(Required::True)
        .description(Some("Entity ID"))
        .schema(Some(RefOr::T(Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::String))
                .into(),
        ))))
        .build();
    params.push(id_param);
    let body = RequestBodyBuilder::new()
        .description(Some(
            "JSON object with fields from _sys_columns to update (camelCase, partial).",
        ))
        .content(
            "application/json",
            Content::new(Some(RefOr::T(entity_body_schema(entity, false)))),
        )
        .required(Some(Required::True))
        .build();
    OperationBuilder::new()
        .summary(Some(format!("Update {} by id", entity.path_segment)))
        .description(Some(format!(
            "Update a single {} by id.",
            entity.path_segment
        )))
        .operation_id(Some(format!("update_{}{}", entity.path_segment, op_suffix)))
        .parameters(Some(params))
        .request_body(Some(body))
        .responses(default_responses().build())
        .build()
}

fn delete_operation(
    entity: &ResolvedEntity,
    op_suffix: &str,
    include_package_id_param: bool,
) -> Operation {
    let mut params = vec![x_tenant_id_header()];
    if include_package_id_param {
        params.push(package_id_param());
    }
    let id_param = ParameterBuilder::new()
        .name("id")
        .parameter_in(ParameterIn::Path)
        .required(Required::True)
        .description(Some("Entity ID"))
        .schema(Some(RefOr::T(Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::String))
                .into(),
        ))))
        .build();
    params.push(id_param);
    OperationBuilder::new()
        .summary(Some(format!("Delete {} by id", entity.path_segment)))
        .description(Some(format!(
            "Delete a single {} by id.",
            entity.path_segment
        )))
        .operation_id(Some(format!("delete_{}{}", entity.path_segment, op_suffix)))
        .parameters(Some(params))
        .responses(
            ResponsesBuilder::new()
                .response("204", Response::new("No Content"))
                .response("400", Response::new("Bad Request"))
                .response("404", Response::new("Not Found"))
                .build(),
        )
        .build()
}

fn bulk_create_operation(
    entity: &ResolvedEntity,
    op_suffix: &str,
    include_package_id_param: bool,
) -> Operation {
    let mut params = vec![x_tenant_id_header()];
    if include_package_id_param {
        params.push(package_id_param());
    }
    let item_schema = entity_body_schema(entity, true);
    let body = RequestBodyBuilder::new()
        .description(Some(
            "JSON array of objects; each has shape from _sys_columns (same as create body).",
        ))
        .content(
            "application/json",
            Content::new(Some(RefOr::T(Schema::Array(
                utoipa::openapi::schema::ArrayBuilder::new()
                    .items(RefOr::T(item_schema))
                    .build(),
            )))),
        )
        .required(Some(Required::True))
        .build();
    OperationBuilder::new()
        .summary(Some(format!("Bulk create {}", entity.path_segment)))
        .description(Some(format!("Create multiple {}.", entity.path_segment)))
        .operation_id(Some(format!(
            "bulk_create_{}{}",
            entity.path_segment, op_suffix
        )))
        .parameters(Some(params))
        .request_body(Some(body))
        .responses(
            ResponsesBuilder::new()
                .response("201", Response::new("Created"))
                .response("400", Response::new("Bad Request"))
                .build(),
        )
        .build()
}

fn bulk_update_operation(
    entity: &ResolvedEntity,
    op_suffix: &str,
    include_package_id_param: bool,
) -> Operation {
    let mut params = vec![x_tenant_id_header()];
    if include_package_id_param {
        params.push(package_id_param());
    }
    let item_schema = entity_body_schema(entity, false);
    let body = RequestBodyBuilder::new()
        .description(Some(
            "JSON array of objects; each must include id and fields from _sys_columns to update (camelCase, partial).",
        ))
        .content(
            "application/json",
            Content::new(Some(RefOr::T(Schema::Array(
                utoipa::openapi::schema::ArrayBuilder::new()
                    .items(RefOr::T(item_schema))
                    .build(),
            )))),
        )
        .required(Some(Required::True))
        .build();
    OperationBuilder::new()
        .summary(Some(format!("Bulk update {}", entity.path_segment)))
        .description(Some(format!("Update multiple {}.", entity.path_segment)))
        .operation_id(Some(format!(
            "bulk_update_{}{}",
            entity.path_segment, op_suffix
        )))
        .parameters(Some(params))
        .request_body(Some(body))
        .responses(default_responses().build())
        .build()
}

/// Add entity paths for one model.
/// - For default model: paths are `{base}/{path_segment}` (no package segment).
/// - For package models: paths are `{base}/package/{package_id}/{path_segment}` with the concrete package id.
fn add_entity_paths(
    mut builder: PathsBuilder,
    base: &str,
    model: &ResolvedModel,
    use_package_param: bool,
    package_id_literal: Option<&str>,
) -> PathsBuilder {
    let path_prefix = if use_package_param {
        match package_id_literal {
            Some(pkg) => format!("{}/package/{}", base, pkg),
            None => format!("{}/package/{{packageId}}", base),
        }
    } else {
        base.to_string()
    };
    let op_suffix = if use_package_param { "_package" } else { "" };

    for entity in &model.entities {
        let seg = &entity.path_segment;
        let list_path = format!("{}/{}", path_prefix, seg);
        let by_id_path = format!("{}/{}/{{id}}", path_prefix, seg);
        let bulk_path = format!("{}/{}/bulk", path_prefix, seg);

        let has_list = entity.operations.iter().any(|o| o == "read");
        let has_create = entity.operations.iter().any(|o| o == "create");
        if has_list || has_create {
            let mut list_item = PathItemBuilder::new();
            if has_list {
                list_item = list_item.operation(
                    HttpMethod::Get,
                    list_operation(entity, op_suffix, use_package_param),
                );
            }
            if has_create {
                list_item = list_item.operation(
                    HttpMethod::Post,
                    create_operation(entity, op_suffix, use_package_param),
                );
            }
            builder = builder.path(list_path, list_item.build());
        }

        let has_read = entity.operations.iter().any(|o| o == "read");
        let has_update = entity.operations.iter().any(|o| o == "update");
        let has_delete = entity.operations.iter().any(|o| o == "delete");
        if has_read || has_update || has_delete {
            let mut by_id_item = PathItemBuilder::new();
            if has_read {
                by_id_item = by_id_item.operation(
                    HttpMethod::Get,
                    read_operation(entity, op_suffix, use_package_param),
                );
            }
            if has_update {
                by_id_item = by_id_item.operation(
                    HttpMethod::Patch,
                    update_operation(entity, op_suffix, use_package_param),
                );
            }
            if has_delete {
                by_id_item = by_id_item.operation(
                    HttpMethod::Delete,
                    delete_operation(entity, op_suffix, use_package_param),
                );
            }
            builder = builder.path(by_id_path, by_id_item.build());
        }

        let has_bulk_create = entity.operations.iter().any(|o| o == "bulk_create");
        let has_bulk_update = entity.operations.iter().any(|o| o == "bulk_update");
        if has_bulk_create || has_bulk_update {
            let mut bulk_item = PathItemBuilder::new();
            if has_bulk_create {
                bulk_item = bulk_item.operation(
                    HttpMethod::Post,
                    bulk_create_operation(entity, op_suffix, use_package_param),
                );
            }
            if has_bulk_update {
                bulk_item = bulk_item.operation(
                    HttpMethod::Patch,
                    bulk_update_operation(entity, op_suffix, use_package_param),
                );
            }
            builder = builder.path(bulk_path, bulk_item.build());
        }
    }
    builder
}

fn kv_namespace_param() -> Parameter {
    ParameterBuilder::new()
        .name("namespace")
        .parameter_in(ParameterIn::Path)
        .required(Required::True)
        .description(Some("KV store namespace (from _sys_kv_stores)."))
        .schema(Some(RefOr::T(Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::String))
                .into(),
        ))))
        .build()
}

fn kv_list_keys_operation() -> Operation {
    OperationBuilder::new()
        .summary(Some("List KV keys in namespace"))
        .description(Some(
            "List all keys and values in the given package and namespace.",
        ))
        .operation_id(Some("kv_list_keys"))
        .parameters(Some(vec![
            x_tenant_id_header(),
            package_id_param(),
            kv_namespace_param(),
        ]))
        .responses(default_responses().build())
        .build()
}

fn kv_key_param() -> Parameter {
    ParameterBuilder::new()
        .name("key")
        .parameter_in(ParameterIn::Path)
        .required(Required::True)
        .description(Some("KV key"))
        .schema(Some(RefOr::T(Schema::Object(
            utoipa::openapi::schema::ObjectBuilder::new()
                .schema_type(SchemaType::new(Type::String))
                .into(),
        ))))
        .build()
}

fn kv_key_operations() -> (Operation, Operation, Operation) {
    let get_op = OperationBuilder::new()
        .summary(Some("Get KV value by key"))
        .description(Some("Get value for key in package and namespace."))
        .operation_id(Some("kv_get"))
        .parameters(Some(vec![
            x_tenant_id_header(),
            package_id_param(),
            kv_namespace_param(),
            kv_key_param(),
        ]))
        .responses(default_responses().build())
        .build();

    let put_op = OperationBuilder::new()
        .summary(Some("Set KV value (upsert)"))
        .description(Some(
            "Set or overwrite value for key. Body is arbitrary JSON.",
        ))
        .operation_id(Some("kv_put"))
        .parameters(Some(vec![
            x_tenant_id_header(),
            package_id_param(),
            kv_namespace_param(),
            kv_key_param(),
        ]))
        .request_body(Some(
            RequestBodyBuilder::new()
                .description(Some("JSON value (string, number, object, or array)"))
                .content(
                    "application/json",
                    Content::new(Some(RefOr::T(json_object_schema()))),
                )
                .required(Some(Required::True))
                .build(),
        ))
        .responses(
            ResponsesBuilder::new()
                .response("200", Response::new("OK"))
                .response("400", Response::new("Bad Request"))
                .build(),
        )
        .build();

    let delete_op = OperationBuilder::new()
        .summary(Some("Delete KV key"))
        .description(Some("Delete key. Returns 204 No Content."))
        .operation_id(Some("kv_delete"))
        .parameters(Some(vec![
            x_tenant_id_header(),
            package_id_param(),
            kv_namespace_param(),
            kv_key_param(),
        ]))
        .responses(
            ResponsesBuilder::new()
                .response("204", Response::new("No Content"))
                .response("404", Response::new("Not Found"))
                .build(),
        )
        .build();

    (get_op, put_op, delete_op)
}

/// Add KV store paths with concrete package ids and {namespace}/{key}.
fn add_kv_paths(
    mut builder: PathsBuilder,
    base: &str,
    package_kv_stores: &HashMap<String, Vec<KvStoreConfig>>,
) -> PathsBuilder {
    for (package_id, stores) in package_kv_stores {
        if stores.is_empty() {
            continue;
        }
        let list_path = format!("{}/package/{}/kv/{{namespace}}", base, package_id);
        let key_path = format!("{}/package/{}/kv/{{namespace}}/{{key}}", base, package_id);

        let list_item = PathItemBuilder::new().operation(HttpMethod::Get, kv_list_keys_operation());
        builder = builder.path(list_path, list_item.build());

        let (get_op, put_op, delete_op) = kv_key_operations();
        let key_item = PathItemBuilder::new()
            .operation(HttpMethod::Get, get_op)
            .operation(HttpMethod::Put, put_op)
            .operation(HttpMethod::Delete, delete_op);
        builder = builder.path(key_path, key_item.build());
    }
    builder
}

/// Add config API paths: install/uninstall package and GET/POST per config kind.
fn add_config_paths(mut builder: PathsBuilder, base: &str) -> PathsBuilder {
    let install_path = format!("{}/config/package", base);
    let install_op = OperationBuilder::new()
        .summary(Some("Install package"))
        .description(Some(
            "Upload a package zip. Zip must contain manifest.json (id, name, version, schema) at root and config JSON files. Use multipart/form-data with field 'file' or 'package' (ZIP file).",
        ))
        .operation_id(Some("config_install_package"))
        .parameters(Some(vec![x_tenant_id_header()]))
        .request_body(Some(
            RequestBodyBuilder::new()
                .description(Some("Multipart form with 'file' or 'package' field containing the ZIP."))
                .content(
                    "multipart/form-data",
                    Content::new(Some(RefOr::T(Schema::Object(
                        ObjectBuilder::new()
                            .schema_type(SchemaType::new(Type::Object))
                            .property(
                                "file",
                                Schema::Object(
                                    ObjectBuilder::new()
                                        .schema_type(SchemaType::new(Type::String))
                                        .format(Some(utoipa::openapi::schema::SchemaFormat::KnownFormat(
                                            utoipa::openapi::schema::KnownFormat::Binary,
                                        )))
                                        .description(Some("ZIP file (manifest.json + config JSONs)"))
                                        .into(),
                                ),
                            )
                            .into(),
                    )))),
                )
                .required(Some(Required::True))
                .build(),
        ))
        .responses(
            ResponsesBuilder::new()
                .response("200", Response::new("OK"))
                .response("400", Response::new("Bad Request"))
                .build(),
        )
        .build();
    let install_item = PathItemBuilder::new().operation(HttpMethod::Post, install_op);
    builder = builder.path(install_path, install_item.build());

    let uninstall_path = format!("{}/config/package/{{packageId}}", base);
    let uninstall_op = OperationBuilder::new()
        .summary(Some("Uninstall package"))
        .description(Some(
            "Revert migrations for the package, delete all _sys_* config and KV data, remove package record.",
        ))
        .operation_id(Some("config_uninstall_package"))
        .parameters(Some(vec![x_tenant_id_header(), package_id_param()]))
        .responses(
            ResponsesBuilder::new()
                .response("200", Response::new("OK"))
                .response("404", Response::new("Not Found"))
                .build(),
        )
        .build();
    let uninstall_item = PathItemBuilder::new().operation(HttpMethod::Delete, uninstall_op);
    builder = builder.path(uninstall_path, uninstall_item.build());

    let config_kinds = [
        ("schemas", "Schema definitions"),
        ("enums", "Enum types"),
        ("tables", "Table definitions"),
        ("columns", "Column definitions"),
        ("indexes", "Index definitions"),
        ("relationships", "Relationship definitions"),
        ("api_entities", "API entity definitions"),
        ("kv_stores", "KV store definitions"),
    ];
    for (kind, description) in config_kinds {
        let path = format!("{}/config/{}", base, kind);
        let get_op = OperationBuilder::new()
            .summary(Some(format!("Get {}", kind)))
            .description(Some(format!(
                "Get {} (from _sys_{}). {}",
                description, kind, "X-Tenant-ID required."
            )))
            .operation_id(Some(format!("config_get_{}", kind)))
            .parameters(Some(vec![x_tenant_id_header()]))
            .responses(default_responses().build())
            .build();
        let post_body = RequestBodyBuilder::new()
            .description(Some(format!("JSON array of {} records.", description)))
            .content(
                "application/json",
                Content::new(Some(RefOr::T(Schema::Array(
                    utoipa::openapi::schema::ArrayBuilder::new()
                        .items(RefOr::T(json_object_schema()))
                        .into(),
                )))),
            )
            .required(Some(Required::True))
            .build();
        let post_op = OperationBuilder::new()
            .summary(Some(format!("Replace {}", kind)))
            .description(Some(format!(
                "Replace {} for the default package. Runs migrations when rows change.",
                kind
            )))
            .operation_id(Some(format!("config_post_{}", kind)))
            .parameters(Some(vec![x_tenant_id_header()]))
            .request_body(Some(post_body))
            .responses(default_responses().build())
            .build();
        let item = PathItemBuilder::new()
            .operation(HttpMethod::Get, get_op)
            .operation(HttpMethod::Post, post_op);
        builder = builder.path(path, item.build());
    }
    builder
}

/// Build full OpenAPI spec for entity APIs: default model paths plus package-scoped paths
/// with concrete package ids, plus KV paths with {namespace}/{key} per package.
pub fn build_spec(
    default_model: &ResolvedModel,
    base_path: &str,
    package_models: &HashMap<String, ResolvedModel>,
    package_kv_stores: &HashMap<String, Vec<KvStoreConfig>>,
) -> OpenApi {
    let server = build_server();
    let mut builder = PathsBuilder::new();
    builder = add_config_paths(builder, base_path);
    builder = add_entity_paths(builder, base_path, default_model, false, None);
    for (package_id, model) in package_models {
        if !model.entities.is_empty() {
            builder = add_entity_paths(builder, base_path, model, true, Some(package_id.as_str()));
        }
    }
    builder = add_kv_paths(builder, base_path, package_kv_stores);
    let paths = builder.build();
    OpenApiBuilder::new()
        .info(
            Info::builder()
                .title("Architect API")
                .version(env!("CARGO_PKG_VERSION"))
                .description(Some("Config APIs (package install/uninstall, schemas, enums, tables, etc.) and entity CRUD + package-scoped entity and KV APIs."))
                .build(),
        )
        .servers(Some(vec![server]))
        .paths(paths)
        .build()
}

/// GET /spec — return OpenAPI JSON for entity APIs. Default (unprefixed) routes come from
/// state.model; package-scoped routes are built by listing _sys_packages and loading each
/// package's config from _sys_* tables (same source of truth as runtime routes).
pub async fn spec_handler(State(state): State<AppState>) -> Json<OpenApi> {
    let default_model = state.model.read().expect("model read lock").clone();
    let base_path = "/api/v1";

    let package_ids = list_package_ids(&state.pool).await.unwrap_or_default();
    let mut package_models: HashMap<String, ResolvedModel> = HashMap::new();
    let mut package_kv_stores: HashMap<String, Vec<KvStoreConfig>> = HashMap::new();
    for package_id in package_ids {
        if let Ok(config) = load_from_pool(&state.pool, &package_id).await {
            if let Ok(model) = resolve(&config) {
                package_models.insert(package_id.clone(), model);
            }
            package_kv_stores.insert(package_id, config.kv_stores);
        }
    }

    let spec = build_spec(
        &default_model,
        base_path,
        &package_models,
        &package_kv_stores,
    );
    Json(spec)
}