use axum::{http::HeaderValue, response::IntoResponse};
use hyper::{header, StatusCode};
use magnetar_core::web_model::{content_type::ContentXrdXml, ContentType};
use serde::Serialize;

use crate::web::{ApiError, ErrorCode};

pub struct XrdXmlExt<T>(pub T);

impl<T: Serialize> IntoResponse for XrdXmlExt<T> {
    fn into_response(self) -> axum::response::Response {
        let mut buf = r#"<?xml version="1.0" encoding="UTF-8"?>"#.to_string();

        match quick_xml::se::to_writer(&mut buf, &self.0) {
            Ok(()) => (
                [(
                    header::CONTENT_TYPE,
                    HeaderValue::from_static(ContentXrdXml.mime_type()),
                )],
                buf.into_bytes(),
            )
                .into_response(),
            Err(e) => ApiError {
                status: StatusCode::INTERNAL_SERVER_ERROR,
                code: ErrorCode("XmlSerializationError".into()),
                message: if cfg!(debug_assertions) {
                    format!("Serialization error: {}", e)
                } else {
                    "Serialization error".to_string()
                },
            }
            .into_response(),
        }
    }
}
