use std::collections::HashSet;

use super::super::Result;
use crate::config::error::Error;
use crate::config::proxy_entry_setting::ProxyEntrySetting;
use crate::config::{address::Address, router_pattern::RouterPattern};
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
pub struct RawProxyEntry {
    pub router: String,
    pub rewrite: bool,
    pub upstreams: Vec<String>,
}

impl RawProxyEntry {
    pub fn take_router_and_setting(self) -> Result<(RouterPattern, ProxyEntrySetting)> {
        let router = self.router.clone()
            .try_into()
            .map_err(|_e| Error::InvalidRouter { s: self.router })?;
        let upstreams = self
            .upstreams
            .into_iter()
            .map(Address::new)
            .collect::<Result<HashSet<_>>>()?;

        Ok((router, ProxyEntrySetting::new(self.rewrite, upstreams)))
    }
}
