server-less-macros 0.6.0

Proc macros for server-less
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
//! Shared OpenAPI generation utilities.
//!
//! This module contains pure functions and types for OpenAPI generation
//! that can be used independently of any HTTP runtime (like axum).
//!
//! Used by both `#[http]` and `#[openapi]` macros.

use heck::ToKebabCase;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use server_less_parse::{HttpMethod, MethodInfo, ParamInfo, ParamLocation};

use crate::context::should_inject_context;

/// Per-method HTTP attribute overrides
#[derive(Default, Clone)]
pub struct RouteOverride {
    pub method: Option<String>,
    /// Span of the `#[route(method = "...")]` literal, for precise error reporting.
    pub method_span: Option<proc_macro2::Span>,
    pub path: Option<String>,
    /// Span of the `#[route(path = "...")]` literal, for precise error reporting.
    pub path_span: Option<proc_macro2::Span>,
    pub skip: bool,
    pub hidden: bool,
    /// Tags for grouping operations in documentation
    pub tags: Vec<String>,
    /// Mark this operation as deprecated
    pub deprecated: bool,
}

impl RouteOverride {
    pub fn parse_from_attrs(attrs: &[syn::Attribute]) -> syn::Result<Self> {
        let mut result = Self::default();

        for attr in attrs {
            if !attr.path().is_ident("route") {
                continue;
            }

            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("skip") {
                    result.skip = true;
                    Ok(())
                } else if meta.path.is_ident("hidden") {
                    result.hidden = true;
                    Ok(())
                } else if meta.path.is_ident("deprecated") {
                    // Support both `deprecated` and `deprecated = true`
                    if meta.input.peek(syn::Token![=]) {
                        let value: syn::LitBool = meta.value()?.parse()?;
                        result.deprecated = value.value();
                    } else {
                        result.deprecated = true;
                    }
                    Ok(())
                } else if meta.path.is_ident("method") {
                    let value: syn::LitStr = meta.value()?.parse()?;
                    result.method_span = Some(value.span());
                    result.method = Some(value.value().to_uppercase());
                    Ok(())
                } else if meta.path.is_ident("path") {
                    let value: syn::LitStr = meta.value()?.parse()?;
                    result.path_span = Some(value.span());
                    result.path = Some(value.value());
                    Ok(())
                } else if meta.path.is_ident("tags") {
                    let value: syn::LitStr = meta.value()?.parse()?;
                    // Support comma-separated tags: tags = "users,admin"
                    result.tags = value
                        .value()
                        .split(',')
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect();
                    Ok(())
                } else {
                    const VALID: &[&str] =
                        &["method", "path", "skip", "hidden", "tags", "deprecated"];
                    let unknown = meta
                        .path
                        .get_ident()
                        .map(|i| i.to_string())
                        .unwrap_or_default();
                    let suggestion = crate::did_you_mean(&unknown, VALID)
                        .map(|s| format!(" — did you mean `{s}`?"))
                        .unwrap_or_default();
                    Err(meta.error(format!(
                        "unknown attribute `{unknown}`{suggestion}\n\
                         \n\
                         Valid attributes: method, path, skip, hidden, tags, deprecated\n\
                         \n\
                         Examples:\n\
                         - #[route(method = \"POST\")]\n\
                         - #[route(path = \"/custom\")]\n\
                         - #[route(skip)] or #[route(hidden)]\n\
                         - #[route(tags = \"users,admin\")]\n\
                         - #[route(deprecated)]\n\
                         \n\
                         Note: Use doc comments for descriptions (first line = summary, full = description)"
                    )))
                }
            })?;
        }

        Ok(result)
    }
}

/// Per-method response customization
#[derive(Default, Clone)]
pub struct ResponseOverride {
    pub status: Option<u16>,
    pub content_type: Option<String>,
    pub headers: Vec<(String, String)>,
    /// Custom description for the response
    pub description: Option<String>,
}

impl ResponseOverride {
    pub fn parse_from_attrs(attrs: &[syn::Attribute]) -> syn::Result<Self> {
        let mut result = Self::default();
        let mut pending_header_name: Option<String> = None;

        for attr in attrs {
            if !attr.path().is_ident("response") {
                continue;
            }

            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("status") {
                    let value: syn::LitInt = meta.value()?.parse()?;
                    result.status = Some(value.base10_parse()?);
                    Ok(())
                } else if meta.path.is_ident("content_type") {
                    let value: syn::LitStr = meta.value()?.parse()?;
                    result.content_type = Some(value.value());
                    Ok(())
                } else if meta.path.is_ident("header") {
                    let name: syn::LitStr = meta.value()?.parse()?;
                    pending_header_name = Some(name.value());
                    Ok(())
                } else if meta.path.is_ident("value") {
                    let value: syn::LitStr = meta.value()?.parse()?;
                    if let Some(name) = pending_header_name.take() {
                        result.headers.push((name, value.value()));
                    }
                    Ok(())
                } else if meta.path.is_ident("description") {
                    let value: syn::LitStr = meta.value()?.parse()?;
                    result.description = Some(value.value());
                    Ok(())
                } else {
                    const VALID: &[&str] =
                        &["status", "content_type", "header", "value", "description"];
                    let unknown = meta
                        .path
                        .get_ident()
                        .map(|i| i.to_string())
                        .unwrap_or_default();
                    let suggestion = crate::did_you_mean(&unknown, VALID)
                        .map(|s| format!(" — did you mean `{s}`?"))
                        .unwrap_or_default();
                    Err(meta.error(format!(
                        "unknown attribute `{unknown}`{suggestion}\n\
                         \n\
                         Valid attributes: status, content_type, header, value, description\n\
                         \n\
                         Examples:\n\
                         - #[response(status = 201)]\n\
                         - #[response(content_type = \"application/octet-stream\")]\n\
                         - #[response(header = \"X-Custom\", value = \"foo\")]\n\
                         - #[response(description = \"User created successfully\")]"
                    )))
                }
            })?;
        }

        if pending_header_name.is_some() {
            return Err(syn::Error::new(
                proc_macro2::Span::call_site(),
                "incomplete `#[response]` attribute: `header` requires a following \
                 `value = \"...\"` argument\n\
                 \n\
                 Example: #[response(header = \"X-Foo\", value = \"bar\")]",
            ));
        }

        Ok(result)
    }
}

/// Split doc comment into summary (first line) and description (full text).
///
/// Returns (summary, description) where:
/// - summary is the first non-empty line (or method name if no docs)
/// - description is the full doc comment (or None if single line or no docs)
fn split_doc_comment(docs: &Option<String>, fallback: &str) -> (String, Option<String>) {
    match docs {
        Some(doc_text) if !doc_text.is_empty() => {
            let first_line = doc_text.lines().next().unwrap_or(fallback).to_string();
            // Only set description if there's more than just the first line
            let description = if doc_text.contains('\n') {
                Some(doc_text.clone())
            } else {
                None
            };
            (first_line, description)
        }
        _ => (fallback.to_string(), None),
    }
}

/// Infer HTTP method from function name prefix.
///
/// Recognized prefixes:
/// - `get_`, `fetch_`, `read_`, `list_`, `find_`, `search_` → GET
/// - `create_`, `add_`, `new_` → POST
/// - `update_`, `set_` → PUT
/// - `patch_`, `modify_` → PATCH
/// - `delete_`, `remove_` → DELETE
///
/// **Fallback:** any name that does not match the above prefixes silently defaults to POST.
/// For example, `execute_payment` or `run_job` will become `POST /execute-payments`.
/// Use `#[route(method = "POST")]` (or another verb) to silence this and make the intent
/// explicit, or rename the method to start with one of the recognized prefixes.
pub fn infer_http_method(name: &str) -> HttpMethod {
    if name.starts_with("get_")
        || name.starts_with("fetch_")
        || name.starts_with("read_")
        || name.starts_with("list_")
        || name.starts_with("find_")
        || name.starts_with("search_")
    {
        HttpMethod::Get
    } else if name.starts_with("create_") || name.starts_with("add_") || name.starts_with("new_") {
        HttpMethod::Post
    } else if name.starts_with("update_") || name.starts_with("set_") {
        HttpMethod::Put
    } else if name.starts_with("patch_") || name.starts_with("modify_") {
        HttpMethod::Patch
    } else if name.starts_with("delete_") || name.starts_with("remove_") {
        HttpMethod::Delete
    } else {
        // NOTE: Unrecognized prefix — falls back to POST. Users writing `execute_payment`
        // or `run_job` will silently get `POST`. Use `#[route(method = "...")]` to be explicit.
        HttpMethod::Post
    }
}

/// Infer a REST path from a method name, HTTP method, and parameter list.
///
/// Uses parameter names to contextually infer `/{id}` paths (e.g. `get_user(id: u32)` → `GET /users/{id}`).
/// See also `server_less_core::infer_path` for the simpler runtime version used in generated code.
pub fn infer_path(method_name: &str, http_method: &HttpMethod, params: &[ParamInfo]) -> String {
    let resource = method_name
        .strip_prefix("get_")
        .or_else(|| method_name.strip_prefix("fetch_"))
        .or_else(|| method_name.strip_prefix("read_"))
        .or_else(|| method_name.strip_prefix("list_"))
        .or_else(|| method_name.strip_prefix("find_"))
        .or_else(|| method_name.strip_prefix("search_"))
        .or_else(|| method_name.strip_prefix("create_"))
        .or_else(|| method_name.strip_prefix("add_"))
        .or_else(|| method_name.strip_prefix("new_"))
        .or_else(|| method_name.strip_prefix("update_"))
        .or_else(|| method_name.strip_prefix("set_"))
        .or_else(|| method_name.strip_prefix("patch_"))
        .or_else(|| method_name.strip_prefix("modify_"))
        .or_else(|| method_name.strip_prefix("delete_"))
        .or_else(|| method_name.strip_prefix("remove_"))
        .unwrap_or(method_name);

    let resource_kebab = resource.to_kebab_case();
    let path_resource = if resource_kebab.ends_with('s') {
        resource_kebab
    } else {
        format!("{}s", resource_kebab)
    };

    // Find the first path-like parameter: one explicitly placed in Path, or an id-like param.
    let id_param = params.iter().find(|p| {
        matches!(p.location.as_ref(), Some(ParamLocation::Path)) || p.is_id
    });

    match http_method {
        HttpMethod::Post => format!("/{}", path_resource),
        HttpMethod::Get
            if method_name.starts_with("list_")
                || method_name.starts_with("search_")
                || method_name.starts_with("find_") =>
        {
            format!("/{}", path_resource)
        }
        HttpMethod::Get | HttpMethod::Put | HttpMethod::Patch | HttpMethod::Delete
            if id_param.is_some() =>
        {
            // Use the actual parameter name instead of hardcoding `id`.
            let p = id_param.unwrap();
            let param_name = p.wire_name.clone().unwrap_or_else(|| p.name_str());
            // A leading underscore is Rust's "unused binding" marker, not part of the
            // semantic name. Strip it so `_id` and `id` map to the same `{id}` segment —
            // otherwise two methods on the same resource path (e.g. GET `{id}` and
            // DELETE `{_id}`) register conflicting matchit patterns. wire_name (explicit)
            // is taken verbatim.
            let param_name = match p.wire_name {
                Some(_) => param_name,
                None => param_name
                    .strip_prefix('_')
                    .map(str::to_string)
                    .unwrap_or(param_name),
            };
            format!("/{}/{{{}}}", path_resource, param_name)
        }
        _ => format!("/{}", path_resource),
    }
}

/// Generate typed OpenAPI paths (Vec<OpenApiPath>)
///
/// Used by protocols to return structured path data for composition.
pub fn generate_openapi_paths(
    prefix: &str,
    methods_with_overrides: &[(MethodInfo, RouteOverride, ResponseOverride)],
) -> syn::Result<TokenStream2> {
    let mut path_constructors = Vec::new();

    for (method, overrides, response_overrides) in methods_with_overrides {
        let method_name = method.name_str();

        let http_method = if let Some(ref m) = overrides.method {
            HttpMethod::parse(m).unwrap_or_else(|| infer_http_method(&method_name))
        } else {
            infer_http_method(&method_name)
        };

        let path = if let Some(ref p) = overrides.path {
            p.clone()
        } else {
            infer_path(&method_name, &http_method, &method.params)
        };
        let full_path = format!("{}{}", prefix, path);
        let http_method_str = http_method.as_str().to_lowercase();

        let (summary, description) = split_doc_comment(&method.docs, &method_name);
        let operation_id = method_name.clone();

        let default_has_body = matches!(
            http_method,
            HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch
        );

        // Collect parameters
        let mut param_constructors = Vec::new();

        for param in &method.params {
            // Skip Context parameters (per-method detection)
            if should_inject_context(&param.ty, &method.params) {
                continue;
            }

            let location = match param.location.as_ref() {
                Some(ParamLocation::Path) => "path",
                Some(ParamLocation::Query) => "query",
                Some(ParamLocation::Body) => continue, // Body params handled separately
                Some(ParamLocation::Header) => "header",
                None => {
                    if param.is_id {
                        "path"
                    } else if default_has_body {
                        continue; // Body params
                    } else {
                        "query"
                    }
                }
            };

            let name = param
                .wire_name
                .clone()
                .unwrap_or_else(|| param.name_str());
            let json_type = server_less_rpc::infer_json_type(&param.ty);
            let required =
                location == "path" || (!param.is_optional && param.default_value.is_none());

            let description = &param.help_text;
            let description_tokens = match description {
                Some(text) => quote! { Some(#text.to_string()) },
                None => quote! { None },
            };
            param_constructors.push(quote! {
                ::server_less::OpenApiParameter {
                    name: #name.to_string(),
                    location: #location.to_string(),
                    required: #required,
                    schema: ::server_less::serde_json::json!({"type": #json_type}),
                    description: #description_tokens,
                    extra: ::server_less::serde_json::Map::new(),
                }
            });
        }

        // Build request body if needed
        let mut body_props = Vec::new();
        for param in &method.params {
            if should_inject_context(&param.ty, &method.params) {
                continue;
            }

            let is_body = match param.location.as_ref() {
                Some(ParamLocation::Body) => true,
                None if default_has_body && !param.is_id => true,
                _ => false,
            };

            if is_body {
                let name = param
                    .wire_name
                    .clone()
                    .unwrap_or_else(|| param.name_str());
                let json_type = server_less_rpc::infer_json_type(&param.ty);
                body_props.push((name, json_type));
            }
        }

        let request_body = if !body_props.is_empty() {
            let prop_insertions: Vec<_> = body_props.iter().map(|(name, ty)| {
                quote! {
                    props.insert(#name.to_string(), ::server_less::serde_json::json!({"type": #ty}));
                }
            }).collect();

            quote! {
                Some({
                    let mut props = ::server_less::serde_json::Map::new();
                    #(#prop_insertions)*
                    ::server_less::serde_json::json!({
                        "required": true,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": props
                                }
                            }
                        }
                    })
                })
            }
        } else {
            quote! { None }
        };

        // Build responses
        let ret = &method.return_info;
        let inferred_code = if ret.is_unit { "204" } else { "200" };
        let success_code = response_overrides
            .status
            .map(|s| s.to_string())
            .unwrap_or_else(|| inferred_code.to_string());
        let has_error = ret.is_result;
        let success_description = response_overrides
            .description
            .clone()
            .unwrap_or_else(|| "Successful response".to_string());

        let responses = if has_error {
            quote! {
                {
                    let mut r = ::server_less::serde_json::Map::new();
                    r.insert(#success_code.to_string(), ::server_less::serde_json::json!({"description": #success_description}));
                    r.insert("400".to_string(), ::server_less::serde_json::json!({"description": "Bad request"}));
                    r.insert("500".to_string(), ::server_less::serde_json::json!({"description": "Internal server error"}));
                    r
                }
            }
        } else {
            quote! {
                {
                    let mut r = ::server_less::serde_json::Map::new();
                    r.insert(#success_code.to_string(), ::server_less::serde_json::json!({"description": #success_description}));
                    r
                }
            }
        };

        // Extract new fields from overrides
        let tags = &overrides.tags;
        let deprecated = overrides.deprecated;
        let has_description = description.is_some();
        let description_str = description.clone().unwrap_or_default();

        path_constructors.push(quote! {
            ::server_less::OpenApiPath {
                path: #full_path.to_string(),
                method: #http_method_str.to_string(),
                operation: ::server_less::OpenApiOperation {
                    summary: Some(#summary.to_string()),
                    description: if #has_description { Some(#description_str.to_string()) } else { None },
                    operation_id: Some(#operation_id.to_string()),
                    tags: vec![#(#tags.to_string()),*],
                    deprecated: #deprecated,
                    parameters: vec![#(#param_constructors),*],
                    request_body: #request_body,
                    responses: #responses,
                    extra: ::server_less::serde_json::Map::new(),
                },
            }
        });
    }

    Ok(quote! {
        vec![#(#path_constructors),*]
    })
}

/// Generate OpenAPI 3.0 specification
pub fn generate_openapi_spec(
    struct_name: &syn::Ident,
    prefix: &str,
    methods_with_overrides: &[(MethodInfo, RouteOverride, ResponseOverride)],
) -> syn::Result<TokenStream2> {
    let mut operation_data = Vec::new();

    for (method, overrides, response_overrides) in methods_with_overrides {
        let method_name = method.name_str();

        let http_method = if let Some(ref m) = overrides.method {
            HttpMethod::parse(m).unwrap_or_else(|| infer_http_method(&method_name))
        } else {
            infer_http_method(&method_name)
        };

        let path = if let Some(ref p) = overrides.path {
            p.clone()
        } else {
            infer_path(&method_name, &http_method, &method.params)
        };
        let full_path = format!("{}{}", prefix, path);
        let http_method_str = http_method.as_str().to_lowercase();

        let (summary, description) = split_doc_comment(&method.docs, &method_name);
        let operation_id = method_name.clone();

        let default_has_body = matches!(
            http_method,
            HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch
        );

        // Group parameters by their actual location (respecting overrides)
        // Filter out Context parameters - they're injected and not part of the API contract
        let mut path_params = Vec::new();
        let mut query_params = Vec::new();
        let mut body_params = Vec::new();
        let mut header_params = Vec::new();

        for param in &method.params {
            // Skip Context parameters - they're injected by the framework (per-method detection)
            if should_inject_context(&param.ty, &method.params) {
                continue;
            }

            match param.location.as_ref() {
                Some(ParamLocation::Path) => path_params.push(param),
                Some(ParamLocation::Query) => query_params.push(param),
                Some(ParamLocation::Body) => body_params.push(param),
                Some(ParamLocation::Header) => header_params.push(param),
                None => {
                    // Infer location based on conventions
                    if param.is_id {
                        path_params.push(param);
                    } else if default_has_body {
                        body_params.push(param);
                    } else {
                        query_params.push(param);
                    }
                }
            }
        }

        let path_param_specs: Vec<_> = path_params
            .iter()
            .map(|p| {
                let name = p.wire_name.clone().unwrap_or_else(|| p.name_str());
                let json_type = server_less_rpc::infer_json_type(&p.ty);
                let description_tokens = match &p.help_text {
                    Some(text) => quote! { Some(#text) },
                    None => quote! { None::<&str> },
                };
                quote! { (#name, "path", #json_type, true, #description_tokens) }
            })
            .collect();

        let query_param_specs: Vec<TokenStream2> = query_params
            .iter()
            .map(|p| {
                let name = p.wire_name.clone().unwrap_or_else(|| p.name_str());
                let json_type = server_less_rpc::infer_json_type(&p.ty);
                let required = !p.is_optional && p.default_value.is_none();
                let description_tokens = match &p.help_text {
                    Some(text) => quote! { Some(#text) },
                    None => quote! { None::<&str> },
                };
                quote! { (#name, "query", #json_type, #required, #description_tokens) }
            })
            .collect();

        let header_param_specs: Vec<TokenStream2> = header_params
            .iter()
            .map(|p| {
                let name = p.wire_name.clone().unwrap_or_else(|| p.name_str());
                let json_type = server_less_rpc::infer_json_type(&p.ty);
                let required = !p.is_optional && p.default_value.is_none();
                let description_tokens = match &p.help_text {
                    Some(text) => quote! { Some(#text) },
                    None => quote! { None::<&str> },
                };
                quote! { (#name, "header", #json_type, #required, #description_tokens) }
            })
            .collect();

        let body_props: Vec<TokenStream2> = body_params
            .iter()
            .map(|p| {
                let name = p.wire_name.clone().unwrap_or_else(|| p.name_str());
                let json_type = server_less_rpc::infer_json_type(&p.ty);
                let required = !p.is_optional && p.default_value.is_none();
                quote! { (#name, #json_type, #required) }
            })
            .collect();
        let has_body_props = !body_props.is_empty();

        let ret = &method.return_info;

        // Determine success code - use override if provided, otherwise infer
        let inferred_code = if ret.is_unit { "204" } else { "200" };
        let success_code = response_overrides
            .status
            .map(|s| s.to_string())
            .unwrap_or_else(|| inferred_code.to_string());

        let error_responses = ret.is_result;

        // Build custom response metadata at macro expansion time
        let has_content_type = response_overrides.content_type.is_some();
        let content_type_value = response_overrides.content_type.as_deref().unwrap_or("");
        let header_insertions: Vec<TokenStream2> = response_overrides
            .headers
            .iter()
            .map(|(name, _)| {
                quote! {
                    headers_obj.insert(#name.to_string(), ::server_less::serde_json::json!({
                        "description": format!("Custom header: {}", #name),
                        "schema": {
                            "type": "string"
                        }
                    }));
                }
            })
            .collect();
        let has_custom_headers = !response_overrides.headers.is_empty();

        // Extract new OpenAPI fields from overrides
        let tags = &overrides.tags;
        let deprecated = overrides.deprecated;
        let has_description = description.is_some();
        let description_str = description.clone().unwrap_or_default();
        let success_description = response_overrides
            .description
            .clone()
            .unwrap_or_else(|| "Successful response".to_string());

        operation_data.push(quote! {
            {
                let path = #full_path;
                let method = #http_method_str;
                let summary = #summary;
                let operation_id = #operation_id;
                let success_code = #success_code;
                let has_error_responses = #error_responses;
                let has_body = #has_body_props;
                let tags: Vec<&str> = vec![#(#tags),*];
                let deprecated = #deprecated;
                let has_description = #has_description;
                let description_str = #description_str;
                let success_description = #success_description;

                let mut parameters: Vec<::server_less::serde_json::Value> = Vec::new();
                #(
                    {
                        let (name, location, schema_type, required, description): (&str, &str, &str, bool, Option<&str>) = #path_param_specs;
                        let mut param = ::server_less::serde_json::json!({
                            "name": name,
                            "in": location,
                            "required": required,
                            "schema": { "type": schema_type }
                        });
                        if let Some(desc) = description {
                            param.as_object_mut().unwrap_or_else(|| unreachable!("BUG: json!({{}}) must produce an Object"))
                                .insert("description".to_string(), ::server_less::serde_json::Value::String(desc.to_string()));
                        }
                        parameters.push(param);
                    }
                )*
                #(
                    {
                        let (name, location, schema_type, required, description): (&str, &str, &str, bool, Option<&str>) = #query_param_specs;
                        let mut param = ::server_less::serde_json::json!({
                            "name": name,
                            "in": location,
                            "required": required,
                            "schema": { "type": schema_type }
                        });
                        if let Some(desc) = description {
                            param.as_object_mut().unwrap_or_else(|| unreachable!("BUG: json!({{}}) must produce an Object"))
                                .insert("description".to_string(), ::server_less::serde_json::Value::String(desc.to_string()));
                        }
                        parameters.push(param);
                    }
                )*
                #(
                    {
                        let (name, location, schema_type, required, description): (&str, &str, &str, bool, Option<&str>) = #header_param_specs;
                        let mut param = ::server_less::serde_json::json!({
                            "name": name,
                            "in": location,
                            "required": required,
                            "schema": { "type": schema_type }
                        });
                        if let Some(desc) = description {
                            param.as_object_mut().unwrap_or_else(|| unreachable!("BUG: json!({{}}) must produce an Object"))
                                .insert("description".to_string(), ::server_less::serde_json::Value::String(desc.to_string()));
                        }
                        parameters.push(param);
                    }
                )*

                let request_body: Option<::server_less::serde_json::Value> = if has_body {
                    let mut properties = ::server_less::serde_json::Map::new();
                    let mut required_props: Vec<String> = Vec::new();
                    #(
                        {
                            let (name, schema_type, required): (&str, &str, bool) = #body_props;
                            properties.insert(name.to_string(), ::server_less::serde_json::json!({
                                "type": schema_type
                            }));
                            if required {
                                required_props.push(name.to_string());
                            }
                        }
                    )*
                    Some(::server_less::serde_json::json!({
                        "required": true,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": properties,
                                    "required": required_props
                                }
                            }
                        }
                    }))
                } else {
                    None
                };

                let mut responses = ::server_less::serde_json::Map::new();

                // Build success response with optional content type and headers
                let mut success_response = ::server_less::serde_json::json!({
                    "description": success_description
                });

                // Add content type if specified
                if #has_content_type {
                    let content_obj = ::server_less::serde_json::json!({
                        #content_type_value: {
                            "schema": {
                                "type": "string"
                            }
                        }
                    });
                    success_response.as_object_mut().unwrap_or_else(|| unreachable!("BUG: json!({{}}) must produce an Object"))
                        .insert("content".to_string(), content_obj);
                }

                // Add custom headers if specified
                if #has_custom_headers {
                    let mut headers_obj = ::server_less::serde_json::Map::new();
                    #(#header_insertions)*
                    success_response.as_object_mut().unwrap_or_else(|| unreachable!("BUG: json!({{}}) must produce an Object"))
                        .insert("headers".to_string(), ::server_less::serde_json::Value::Object(headers_obj));
                }

                responses.insert(success_code.to_string(), success_response);

                if has_error_responses {
                    responses.insert("400".to_string(), ::server_less::serde_json::json!({
                        "description": "Bad request"
                    }));
                    responses.insert("500".to_string(), ::server_less::serde_json::json!({
                        "description": "Internal server error"
                    }));
                }

                let mut operation = ::server_less::serde_json::json!({
                    "summary": summary,
                    "operationId": operation_id,
                    "responses": responses
                });

                // Add description if specified
                if has_description {
                    operation.as_object_mut().unwrap_or_else(|| unreachable!("BUG: json!({{}}) must produce an Object"))
                        .insert("description".to_string(), ::server_less::serde_json::Value::String(description_str.to_string()));
                }

                // Add tags if specified
                if !tags.is_empty() {
                    let tags_json: Vec<::server_less::serde_json::Value> = tags.iter()
                        .map(|t| ::server_less::serde_json::Value::String(t.to_string()))
                        .collect();
                    operation.as_object_mut().unwrap_or_else(|| unreachable!("BUG: json!({{}}) must produce an Object"))
                        .insert("tags".to_string(), ::server_less::serde_json::Value::Array(tags_json));
                }

                // Add deprecated flag if true
                if deprecated {
                    operation.as_object_mut().unwrap_or_else(|| unreachable!("BUG: json!({{}}) must produce an Object"))
                        .insert("deprecated".to_string(), ::server_less::serde_json::Value::Bool(true));
                }

                if !parameters.is_empty() {
                    operation.as_object_mut().unwrap_or_else(|| unreachable!("BUG: json!({{}}) must produce an Object"))
                        .insert("parameters".to_string(), ::server_less::serde_json::Value::Array(parameters));
                }

                if let Some(body) = request_body {
                    operation.as_object_mut().unwrap_or_else(|| unreachable!("BUG: json!({{}}) must produce an Object"))
                        .insert("requestBody".to_string(), body);
                }

                (path.to_string(), method.to_string(), operation)
            }
        });
    }

    Ok(quote! {
        {
            let mut paths = ::server_less::serde_json::Map::new();

            #(
                {
                    let (path, method, operation): (String, String, ::server_less::serde_json::Value) = #operation_data;
                    let path_item = paths.entry(path)
                        .or_insert_with(|| ::server_less::serde_json::json!({}));
                    if let ::server_less::serde_json::Value::Object(map) = path_item {
                        map.insert(method, operation);
                    }
                }
            )*

            ::server_less::serde_json::json!({
                "openapi": "3.0.0",
                "info": {
                    "title": stringify!(#struct_name),
                    "version": "0.1.0"
                },
                "paths": paths
            })
        }
    })
}