use std::error::Error;
use std::fmt;
use std::time::SystemTime;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TimeParseError {
    message: String,
}

impl TimeParseError {
    fn new(error: humantime::TimestampError) -> Self {
        Self {
            message: error.to_string(),
        }
    }
}

impl fmt::Display for TimeParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "expected RFC3339 timestamp like 2026-06-07T12:00:00Z ({})",
            self.message
        )
    }
}

impl Error for TimeParseError {}

pub fn parse_time(value: &str) -> Result<SystemTime, TimeParseError> {
    humantime::parse_rfc3339(value.trim()).map_err(TimeParseError::new)
}

pub fn format_time(value: SystemTime) -> String {
    humantime::format_rfc3339_nanos(value).to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_rfc3339() {
        let time = parse_time("2026-06-07T12:00:00Z").expect("timestamp parses");
        assert_eq!(format_time(time), "2026-06-07T12:00:00.000000000Z");
    }

    #[test]
    fn rejects_date_only() {
        assert!(parse_time("2026-06-07").is_err());
    }
}
