// Copyright 2023 Salesforce, Inc. All rights reserved.
use crate::error::CorsError;
use crate::model::resource::protected_resource::ResponseType;
use crate::model::response::headers::CorsHeader;

///
/// Processes different [CorsHeader] processor, adding the necessary headers for each type of
/// request.
///
#[derive(Default)]
pub struct CorsResponse {}

impl CorsResponse {
    ///
    /// Processes different [CorsHeader] processor, adding the necessary headers for each type of
    /// request.
    ///
    /// Returns the headers wrapped in a [ResponseType], or [Err] if some processor
    /// failed to validate.
    ///
    pub fn add_headers(
        &self,
        processor: Vec<&dyn CorsHeader>,
        is_preflight: bool,
    ) -> Result<ResponseType, CorsError> {
        let processor_result: Result<Vec<_>, CorsError> =
            processor.into_iter().map(|header| header.add()).collect();

        processor_result.map(|headers| {
            let flattened_headers = headers.into_iter().flatten().collect();

            if is_preflight {
                ResponseType::Preflight(flattened_headers)
            } else {
                ResponseType::Main(flattened_headers)
            }
        })
    }
}
