use std::str::FromStr;
use lazy_static::lazy_static;
use regex::Regex;
use crate::config::error::Error;
use super::Result;

lazy_static! {
    static ref DOMAIN_REGEX: Regex =
        Regex::new(r"^([a-zA-Z0-9.-]+)$").expect("Failed to compile regex");
}
#[derive(Debug, Clone)]
pub struct Domain(String);

impl Domain {
    pub fn new<S: AsRef<str> + Into<String>>(s: S) -> Result<Self> {
        if DOMAIN_REGEX.is_match(s.as_ref()) {
            Ok(Self(s.into()))
        } else {
            Err(Error::InvalidDomain { s: s.into() })?
        }
    }
}

impl From<Domain> for String {
    fn from(value: Domain) -> Self {
        value.0
    }
}

impl TryFrom<String> for Domain {
    type Error = Error;
    fn try_from(value: String) -> Result<Self> {
        Self::new(value)
    }
}

impl FromStr for Domain {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        Self::new(s)
    }
}
