//! Form body parser

use crate::core::CoreError;
use bytes::Bytes;
use serde::de::DeserializeOwned;

/// Maximum body size for form parsing (1MB)
const MAX_SIZE: usize = 1024 * 1024;

/// Form parser
///
/// Parses `application/x-www-form-urlencoded` request bodies with a 1MB size limit.
/// Use `parse_as<T>()` to deserialize into a specific type.
#[derive(Debug, Clone, Default)]
pub struct FormParser;
impl FormParser {
    /// Parse form bytes into a specific type
    ///
    /// Returns `CoreError::PayloadTooLarge` (413) if the body exceeds 1MB.
    /// Returns `CoreError::BodyParseError` (400) if the form data is invalid.
    pub async fn parse_as<T: DeserializeOwned>(body: &Bytes) -> Result<T, CoreError> {
        if body.len() > MAX_SIZE {
            return Err(CoreError::payload_too_large(format!(
                "Request body too large: {} bytes (max: {} bytes)",
                body.len(),
                MAX_SIZE
            )));
        }

        let text = String::from_utf8(body.to_vec()).map_err(|e| {
            CoreError::body_parse_error(format!("Form data is not valid UTF-8: {}", e))
        })?;

        serde_urlencoded::from_str(&text)
            .map_err(|e| CoreError::body_parse_error(format!("Invalid form data: {}", e)))
    }
}
