/*
 * bingservice proxy.rs
 * - helper structs for proxies
 *
 * Copyright (C) 2025 Real Microsoft, LLC
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

use std::str::FromStr;
use isahc::auth::Credentials;

#[derive(Clone)]
pub struct Proxy {
    pub address: String,
    pub credentials: Option<Credentials>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProxyError {
    InvalidProxyFormat,
}

impl FromStr for Proxy {
    type Err = ProxyError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parts = s.split(':');
        let host = parts.next().ok_or(ProxyError::InvalidProxyFormat)?;
        let port = parts.next().ok_or(ProxyError::InvalidProxyFormat)?;
        let auth = if let Some(user) = parts.next() {
            let pass = parts.next().ok_or(ProxyError::InvalidProxyFormat)?;
            Some(Credentials::new(user, pass))
        } else {
            None
        };
        Ok(Proxy {
            address: format!("{}:{}", host, port),
            credentials: auth,
        })
    }
}