//! HTTP status code attribute parsing

use syn::{Attribute, Result};

use crate::ir::HttpStatusValue;

/// Parse `#[http_status(...)]` attribute.
pub(crate) fn parse_http_status(attrs: &[Attribute]) -> Result<Option<HttpStatusValue>> {
    for attr in attrs {
        if attr.path().is_ident("http_status") {
            if let Ok(lit) = attr.parse_args::<syn::LitInt>() {
                let status: u16 = lit.base10_parse()?;

                if let Err(e) = http::StatusCode::from_u16(status) {
                    return Err(syn::Error::new_spanned(
                        lit,
                        format!("invalid HTTP status code: {e}"),
                    ));
                }

                return Ok(Some(HttpStatusValue::Code(status)));
            }

            let path: syn::Path = attr.parse_args()?;
            return Ok(Some(HttpStatusValue::Path(path)));
        }
    }
    Ok(None)
}
